【LeetCode】Longest Common Prefix(最长公共前缀)
这道题是LeetCode里的第14道题。
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串
""
。示例 1:
输入: ["flower","flow","flight"] 输出: "fl"
示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母
a-z
。
总共有 5 种思路:
- 所求的最长公共前缀子串一定是每个字符串的前缀子串,所以随便选择一个字符串作为标准,把它的前缀子串与其它所有字符串进行判断,看是否是它们所有字符串的前缀子串。
- 列出所有的字符串的前缀子串,将它们合并后排序,找出其中个数为 n 且最长的子串。
- 纵向扫描,从下标 0 开始,逐一判断每个字符串的下标是否相等,直到遇见不全相同的下标位置为止。
- 横向扫描:前两个字符串找公共子串,将其结果和第三条字符串同样找公共子串,直到最后一个字符串为止。
- 借助 trie 字典树,将这些字符串存储到 trie 树中,那么 trie 树的第一个分叉口之前的单分支树的就是所求。
这里我使用纵向扫描。
解题代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)return "";
if(strs.length == 1)return strs[0];
StringBuffer res = new StringBuffer();
StringBuffer shortly = new StringBuffer(strs[0]);
int shortlyIndex = 0;
for(int i=1; i<strs.length; i++) {
if(strs[i].equals(""))return "";
if(shortly.length() > strs[i].length()) {
shortly.delete(0, shortly.length());
shortly.append(strs[i]);
shortlyIndex = i;
}
}
strs[shortlyIndex] = strs[0];
strs[0] = shortly.toString();
//System.out.println(shortly);
for(int i=0; i<shortly.length(); i++) {
for(int j=1; j<strs.length; j++) {
if(strs[0].charAt(i) != strs[j].charAt(i)) {
return res.toString();
}
if(j == strs.length - 1) {
res.append(strs[0].charAt(i));
}
}
}
return res.toString();
}
}
提交结果:
个人总结:
题目有坑!strs = [] 的情况万万没想到。而且我这部分代码也是可以简化的,我这样写就是为了避免一些下标的越界错误。但其实没多大的必要。