14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
思路:两个循环必不可少
public String longestCommonPrefix(String[] strs) {
String commonStr = "";
if (strs.length==0){
return commonStr;
}
commonStr = strs[0];
for (int i=1;i<strs.length;i++){
commonStr = CommonPrefix(commonStr,strs[i]);
}
return commonStr;
}
public String CommonPrefix(String str1, String str2){
StringBuilder commonStr = new StringBuilder();
int i = 0;
while(i<str1.length()&&i<str2.length()&&str1.charAt(i)==str2.charAt(i)){
commonStr.append(str1.charAt(i));
i++;
}
return commonStr.toString();
}
}
C++ code
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size()==0) return "";
string commonPre = strs[0];
for (int i=1;i<strs.size();i++){
commonPre = getCommon(commonPre,strs[i]);
}
return commonPre;
}
string getCommon(string str1, string str2){
string newCommon = "";
int len = min(str1.size(),str2.size());
for(int i=0; i<len && str1[i]==str2[i]; i++){
newCommon += str1[i];
}
return newCommon;
}
};