【Leetcode Algorithm】Longest Common Prefix
2015-07-02 15:09
453 查看
Write a function to find the longest common prefix string amongst an array of strings.自己的代码:
Write a function to find the longest common prefix string amongst an array of strings.自己的代码:
123456789101112131415161718192021222324252627282930 | public class Solution { public String longestCommonPrefix(String[] strs) { //当字符串数组strs为空,前缀为空字符串 if (strs.length== 0 ){ return "" ; } //定义初始前缀 String prefix = strs[ 0 ]; //将前缀和各字符串依次比较 for ( int i= 0 ;i<strs.length;i++){ //如果前缀为空,或者字符串数组strs的某个子字符串为空,返回空字符串 if (prefix.length()== 0 ||strs[i].length()== 0 ){ return "" ; } //找到前缀字符串和当前字符串之间的最短长度 int len = Math.min(prefix.length(),strs[i].length()); //比较前缀字符串和当前字符串,找出公共前缀 int j= 0 ; for (;j<len;j++){ //如果有不同的字符,直接跳出循环 if (prefix.charAt(j)!=strs[i].charAt(j)){ break ; } } //更新前缀 prefix = prefix.substring( 0 ,j); } return prefix; } } |
123456789101112131415161718192021222324252627282930 | public class Solution { public String longestCommonPrefix(String[] strs) { //当字符串数组strs为空,前缀为空字符串 if (strs.length== 0 ){ return "" ; } //定义初始前缀 String prefix = strs[ 0 ]; //将前缀和各字符串依次比较 for ( int i= 0 ;i<strs.length;i++){ //如果前缀为空,或者字符串数组strs的某个子字符串为空,返回空字符串 if (prefix.length()== 0 ||strs[i].length()== 0 ){ return "" ; } //找到前缀字符串和当前字符串之间的最短长度 int len = Math.min(prefix.length(),strs[i].length()); //比较前缀字符串和当前字符串,找出公共前缀 int j= 0 ; for (;j<len;j++){ //如果有不同的字符,直接跳出循环 if (prefix.charAt(j)!=strs[i].charAt(j)){ break ; } } //更新前缀 prefix = prefix.substring( 0 ,j); } return prefix; } } |
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)