Write a function to find the longest common prefix string amongst an array of strings.
https://oj.leetcode.com/problems/longest-common-prefix/
思路1:以第一个字符串为基准,依次比较后面字符串每一位的情况,如有不相同或者有字符串提前结束即返回。
public class Solution {
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if(n<1)
return "";
int len0 = strs[0].length();
int i, j;
outer: for (i = 0; i < len0; i++) {
char cur = strs[0].charAt(i);
for (j = 1; j < n; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
break outer;
}
}
}
return strs[0].substring(0, i);
}
public static void main(String[] args) {
System.out.println(new Solution().longestCommonPrefix(new String[] {
"abbasda", "abb", "abbc" }));
System.out.println(new Solution().longestCommonPrefix(new String[] {
"", "ab", "ac" }));
System.out.println(new Solution()
.longestCommonPrefix(new String[] { "abc" }));
System.out.println(new Solution()
.longestCommonPrefix(new String[] {}));
}
}
来源:oschina
链接:https://my.oschina.net/u/1584603/blog/283660