LeetCode 14 Longest Common Prefix(最长公共前缀)
2017-03-05 16:06
585 查看
题目链接:https://leetcode.com/problems/longest-common-prefix/?tab=Description
Problem: 找出给定的string数组中最长公共前缀
由于是找前缀,因此调用indexOf函数应当返回0(如果该字符子串为字符串的前缀时),如果不是则返回-1
Return:
the index of the first occurrence of the specified substring, or
参考代码:
Problem: 找出给定的string数组中最长公共前缀
由于是找前缀,因此调用indexOf函数应当返回0(如果该字符子串为字符串的前缀时),如果不是则返回-1
Return:
the index of the first occurrence of the specified substring, or
-1if there is no such occurrence.
参考代码:
package leetcode_50; /*** * * @author pengfei_zheng * 最长公共前缀 */ public class Solution14 { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return "";//字符串数组为空或者长度为0 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(最长公共前缀)
- LeetCode 14 Longest Common Prefix(最长公共前缀)(String)
- LeetCode 14 Longest Common Prefix(最长公共前缀)
- [C++]LeetCode 14: Longest Common Prefix(最长公共前缀)
- LeetCode-14-Longest-Common-Prefix 求若干字符串的最大公共前缀
- LeetCode 14 Longest Common Prefix 最长前缀
- Leet Code 14 Longest Common Prefix - 最长公共前缀 - Java
- 【LeetCode-面试算法经典-Java实现】【014-Longest Common Prefix(最长公共前缀)】
- LeetCode Longest Common Prefix 最长公共前缀
- [leetcode] Longest Common Prefix 字符窜最长公共前缀判断
- [转][LeetCode]Longest Common Prefix ——求字符串的最长公共前缀
- LeetCode | Longest Common Prefix(最长公共前缀)
- [LeetCode]32. Longest Common Prefix最长公共前缀
- leetcode:java.T014_LongestCommonPrefix--写一个函数找出一个字串所数组中的最长的公共前缀
- 每日一练之Longest Common Prefix【LeetCode No.14】——求字符串的最长公共前缀
- Lettcode_14_Longest Common Prefix——查找字符串数组中最长公共前缀字符串
- LeetCode 第十四题 Longest Common Prefix(最长公共前缀)
- Leetcode:Longest Common Prefix 最长公共前缀
- (LeetCode)Longest Common Prefix --- 最长公共前缀