Write a function to find the longest common prefix string amongst an array of strings.
先把排好序的前两个字符串的最大前缀求出来,然后看这个前缀是否是其他字符串的前缀,如果不是,缩短这个前缀再看是否是其他字符串的前缀
class Solution { public: string longestCommonPrefix(vector<string> &strs) { string result; int len = strs.size(); if(len==0) return ""; else if(len==1) return strs[0]; sort(strs.begin(),strs.end()); string str1 = strs[0]; string str2 = strs[1]; int len1 = str1.size()>str2.size()?str2.size():str1.size(); int i; for( i=0;i<len1;i++){ if(str1[i]!=str2[i]){ result = str1.substr(0,i); break; } }//end for if(i==len1) result = str1.substr(0,len1); int length = result.size(); while(length>=0){ string theS = result.substr(0,length); int i; for(i=2;i<len;i++){ if(strs[i].substr(0,length)!= theS) break; } if(i==len) return theS; length--; } return result; }//end func };