问题描述:
Write a function to find the longest common prefix string amongst an array of strings.
即 最长公共前缀。
思路: 一串字符串的最长公共前缀一定不长于其中任意两个字符串的公共前缀。 且任意两个字符串的公共前缀的长豆不会大于最短的字符串的长度。 第一次取前两个求得longest common prefix ,得到的结果与第三个一起求,每次把结果作为新的子串比较。
注意特殊情况(字符串数组为空,或者只有一个字符串)
代码:
public class Solution {
static public String findlp (String s1 , String s2){
String a = "";
int m = s1.length() < s2.length() ? s1.length() : s2.length();
if(m==0){
return "";
}else{
for(int i=0; i <m; i++){
if( ! s1.substring(i, i+1).equals(s2.substring(i, i+1))){
return a;
}else{
a = a + s1.substring(i, i+1);
}
}
}
return a;
}
public String longestCommonPrefix(String[] strs) {
String a = "";
if(strs.length ==0){
return a;
}
if(strs.length ==1){
return strs[0];
}
a = findlp(strs[0],strs[1]);
if(strs.length==2){
return a;
}
for(int i = 2; i < strs.length ; i++){
a = findlp(a,strs[i]);
}
return a;
}
}
结果:
117 / 117 test cases passed.
| Status: Accepted |
Runtime:
16 ms
|