leetcode 14. Longest Common Prefix
2016-06-05 17:15
363 查看
Write a function to find the longest common prefix string amongst an array of strings.
在一个字符串数组中找出最长公共前缀
遍历判断第一个字符串的每个字符与其他字符串的相应位置的字符
public class A14LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
if(strs.length == 1 || "".equals(strs[0])) return strs[0];
int i, j;
for(i = 0; i < strs[0].length(); i++) {
for(j = 1; j < strs.length; j++) {
if(i >= strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i))
return strs[0].substring(0, i);
}
}
return strs[0].substring(0, i);
}
}
在一个字符串数组中找出最长公共前缀
遍历判断第一个字符串的每个字符与其他字符串的相应位置的字符
public class A14LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
if(strs.length == 1 || "".equals(strs[0])) return strs[0];
int i, j;
for(i = 0; i < strs[0].length(); i++) {
for(j = 1; j < strs.length; j++) {
if(i >= strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i))
return strs[0].substring(0, i);
}
}
return strs[0].substring(0, i);
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [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_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- 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 题解