leetcode longest common prefix

文章目录

tips

以一个串为基准,其它串依次与该串比较,不断调整缩小common prefix

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0) return "";
int rightMax = strs[0].size();
for(int i = 1; i < strs.size(); ++i) {
for(int j = 0; j < rightMax; j++) {
if(strs[i][j] != strs[0][j]) {
rightMax = j;
}
}
}
return strs[0].substr(0, rightMax);
}
};