public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int minLen = Integer.MAX_VALUE;
for (String s : strs) {
minLen = s.length() < minLen ? s.length() : minLen;
}
for (int i = 0; i < minLen; i++) {
for (int j = 0; j < strs.length - 1; j++) {
String s1 = strs[j];
String s2 = strs[j + 1];
if (s1.charAt(i) != s2.charAt(i)) {
return s1.substring(0, i);
}
}
}
return strs[0].substring(0, minLen);
}
}
2016年6月18日星期六
[LintCode] #78 Longest Common Prefix
Problem: http://www.lintcode.com/en/problem/longest-common-prefix/
订阅:
博文评论 (Atom)
没有评论:
发表评论