leetcode 14. Longest Common Prefix
2018-01-07 15:29
323 查看
题目
Write a function to find the longest common prefix string amongst an array of strings.解
class Solution { public String longestCommonPrefix(String[] strs) { //return ""; if(strs==null || strs.length==0){ return ""; } //找出最短字符串 int s=0; for(int j=1;j<strs.length;j++){ if(strs[j].length()<strs[s].length()){ s=j; } } //若最短字符串的长度为0,直接返回空字符串即可 if(strs[s].length()==0) return ""; //从最短字符串的最长距离到最短距离进行测试 for(int i=strs[s].length();i>0;i--){ String prefixStr=strs[s].substring(0,i); int count=0; for(int j=0;j<strs.length;j++){ if(strs[j].substring(0,i).equals(prefixStr)){ count++; } } if(count==strs.length){ return prefixStr; } } return ""; } }
优解
public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while(i < strs.length){ while(strs[i].indexOf(pre) != 0) pre = pre.substring(0,pre.length()-1); i++; } return pre; }
小结
可以考虑字符串匹配方面的内容。相关文章推荐
- [LeetCode] 14 - Longest Common Prefix
- leetcode 14: Longest Common Prefix (C#版)
- LeetCode 14.Longest Common Prefix
- Leetcode-14: Longest Common Prefix
- LeetCode14. Longest Common Prefix
- leetcode14:Longest Common Prefix
- LeetCode - 14. Longest Common Prefix
- LeetCode--14. Longest Common Prefix
- DAY7:leetcode #14 Longest Common Prefix
- 14、LeetCode--Longest Common Prefix
- Leetcode 14. Longest Common Prefix
- [Leetcode] 14. Longest Common Prefix
- leetcode 14. Longest Common Prefix
- 【leetcode c++】14Longest Common Prefix
- 【Leetcode】14. Longest Common Prefix
- [LeetCode]14. Longest Common Prefix
- Leetcode_14_Longest Common Prefix
- LeetCode-14. Longest Common Prefix
- Leetcode 14. Longest Common Prefix
- LeetCode 14. Longest Common Prefix