leetcode第十四题(easy)——Longest Common Prefix
来源:互联网 发布:linux cp命令 时间 编辑:程序博客网 时间:2024/04/28 07:15
题目描述如下:
Write a function to find the longest common prefix string amongst an array of strings.
一开始搞错了题目的意思,以为是两两字符串相比较,求出最大长度前缀,结果是所有的字符串相比,求出共同的最大长度前缀。
如何来取得两个字符串的最长前缀呢?
刚开始是通过这种方法来获得,str1.startsWith(str2.substring(0,k)),通过循环k来获得。
后来网上参考了一下别人的思路,又得到了一种特别的求法:
<span style="white-space:pre"></span>for(k=0;k<len;k++){ if(prefix.charAt(k)!=strs[i].charAt(k)){ break; } } prefix=strs[i].substring(0,k);
此题思路如下:
首先得考虑特殊情况:当字符串数组strs中没字符串,即length=0时,最大前缀为“”;当字符串数组strs中有空串“”时,最大前缀也为“”。
然后是正常情况:先将数组第一个元素置为最长前缀prefix,随后与剩下的每个元素一一比较,因为2个字符串的最长公共前缀,其长度肯定不会超过最短的字符串的长度,所以取长度短的作为len。最后取得的作为prefix
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0){ return ""; } String prefix=strs[0]; for(int i=1;i<strs.length;i++){ if(prefix==""||strs[i]==""){ return ""; } int len = prefix.length()>strs[i].length()?strs[i].length():prefix.length(); int k; for(k=0;k<len;k++){ if(prefix.charAt(k)!=strs[i].charAt(k)){ break; } } prefix=strs[i].substring(0,k); } return prefix; }}
0 0
- leetcode第十四题(easy)——Longest Common Prefix
- Leetcode 14.Longest Common Prefix——python (easy)
- Leetcode[Easy] - Longest Common Prefix
- LeetCode—Longest Common Prefix
- LeetCode 第十四题 Longest Common Prefix(最长公共前缀)
- [Leetcode 14, Easy] Longest common prefix
- <LeetCode><Easy> 14 Longest Common Prefix
- Leetcode 14. Longest Common Prefix (Easy) (cpp)
- LeetCode 14. Longest Common Prefix (easy)
- LeetCode-Easy-Java-Longest Common Prefix
- LeetCode-Easy刷题(4) Longest Common Prefix
- 【LeetCode】LeetCode——第14题:Longest Common Prefix
- LeetCode刷题(C++)——Longest Common Prefix(Easy)
- LeetCode——Longest Common Prefix
- LeetCode——Longest Common Prefix
- Longest Common Prefix —— Leetcode
- leetcode——Longest Common Prefix
- leetcode 014 —— Longest Common Prefix
- mahout spectral聚类1
- 项目0:是春哥啊
- 职业规划
- java object之clone
- Android之Volley
- leetcode第十四题(easy)——Longest Common Prefix
- SDKD 14级组队练习赛(一) D 数组存储二叉树并递归遍历
- floyd算法
- Java基础-Class类
- MySQL与Oracle 数据类型比较
- setTimeout()中函数加双引号和不加有什么区别?
- 社説 20150517 米軍オスプレイ 横田配備で即応力が向上する
- 详解 /etc/group
- 设备IO之一(mmap、直接IO以及异步IO)