您的位置:首页 > 其它

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode