题目:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
思路:
把字符串数组排序一下。然后按照常理疯狂遍历就好了。
代码实现:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() <= 0){
return "";
}
string ans="";
sort(strs.begin(), strs.end()); // 按从小到大排序,字符串短的更靠前些
for (int i = 0; i < strs[0].length(); ++i){
for (int j = 1; j < strs.size(); ++j){
if (strs[0][i] != strs[j][i]){
return ans;
}
}
ans.append(1,strs[0][i]);
}
return ans;
}
};
discuss:
还是常规方法,挨个遍历。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string toReturn;
if (!strs.size()){
return toReturn;
}
for (int i = 0; i < strs[0].size(); ++i){
char curr = strs[0][i]; // 遍历第一个string
for (int j = 1; j < strs.size(); ++j){ // 遍历其余string
if (i > strs[j].size()-1 || curr != strs[j][i]){
return toReturn;
}
}
toReturn.push_back(curr);
}
return toReturn;
}
};