您的位置:首页 > 编程语言 > Java开发

LeetCode 14 : Longest Common Prefix (Java)

2015-12-03 20:25 796 查看
解题思路:最长公共前缀肯定不会超过最短字符串的长度。所以先获得最短字符串的长度。然后一个二层循环,外层循环是最短字符串长度的每个位置,内层循环是每个字符串对应的这个位置的字符,然后比较所以字符串这个位置的字符是否相等,如果相同,将该字符加入结果中,否则返回结果。

public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0)
return "";
int minLen = strs[0].length();
for(int i=0;i<strs.length;i++) {
if(strs[i].length() < minLen) {
minLen = strs[i].length();
}
}

String result = "";
for(int i=0;i<minLen;i++) {
char c = strs[0].charAt(i);
for(int j=1;j<strs.length;j++) {
if(strs[j].charAt(i) != c) {
return result;
}
}
result = result + c;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  String