LeetCode原题:Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
主要内容:
返回给定字符串数组里面所有字符串的最长公共前缀
解题思想:
1.一般以第一个字符串作为对比,将其依次与后续字符串的固定位置上的字符进行是否相等的比较,如果全部相等,那么将该字符加入我们所要返回的目标字符串里,固定位置移动的距离取决于所以字符串中size最小的字符串的size
2.数组中只有一个字符串的时候单独考虑
参考C++代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string s = "";
int z = strs.size();
int zz = 0;
int c = 0;
for(int i = 0; i < z; i++) {
if(strs[i].size() < zz || i == 0) zz = strs[i].size();
}
if(z == 1) s += strs[0];
else {
for(int j = 0; j < zz; j++) {
for(int i = 1; i < z; i++) {
if(strs[0][j] == strs[i][j]) c++;
else break;
}
if (c == z - 1) {
s += strs[0][j];
c = 0;
} else break;
}
}
return s;
}
};