No.14 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
求一组string的最长公共前缀
想法:找到最短的那个,然后依次对比
典型的字符串操作,从前向后比较即可
1 #include "stdafx.h" 2 #include <string> 3 #include <vector> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 8 class Solution 9 { 10 public: 11 string longestCommonPrefix(vector<string> &strs) 12 {//求一组string的最长公共前缀 13 //想法:找到最短的那个,然后依次对比 14 int size = strs.size(); 15 string res(""); 16 if(size == 0) 17 return res; 18 19 int shortestCount = strs[0].size();//记录最短的 20 for(int i=1; i<size; i++) 21 { 22 if(strs[i].size() < shortestCount) 23 shortestCount = strs[i].size(); 24 } 25 26 //从前向后比较shortestCount位 27 for(int i=0; i<shortestCount; i++) 28 { 29 auto tmp = strs[0][i]; 30 for(int j=1; j<size; j++) 31 { 32 if(strs[j][i] != tmp) 33 return res; 34 } 35 res += tmp; 36 } 37 return res; 38 } 39 }; 40 41 int main() 42 { 43 Solution sol; 44 string data[] = {"a","abc","ad"}; 45 vector<string> test(data,data+3); 46 cout << sol.longestCommonPrefix(test)<<endl; 47 48 string data1[] = {"ad","abc","ad",""}; 49 vector<string> test1(data1,data1+4); 50 cout << sol.longestCommonPrefix(test1)<<endl; 51 }