Contents
1
2
3
4
/*
* Write a function to find the longest common prefix string amongst an array
* of strings.
*/
  • 求多个字符串的最长公共前缀。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
int ans = strs[0].size();
for(int i = 1; i < strs.size(); i++){
int s1 = strs[0].size();
int s2 = strs[i].size();
int mins = s1 < s2 ? s1 : s2;
ans = ans < mins ? ans : mins;
for(int j = 0; j < mins; j++){
if(strs[0][j] != strs[i][j]){
ans = ans < j ? ans : j;
break;
}
}
}
if(ans == -1){
return "";
}else{
return strs[0].substr(0, ans);
}
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
int right_most = strs[0].length();
for(int i = 1; i < strs.length; i++) {
right_most = Math.min(right_most, strs[i].length());
for(int j = 0; j < right_most; j++) {
if(strs[0].charAt(j) != strs[i].charAt(j)) {
right_most = j;
break;
}
}
}
return strs[0].substring(0, right_most);
}
}
Contents