题解 | #最长公共前缀#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
} else if (strs.length == 1) {
return strs[0];
}
StringBuffer sb = new StringBuffer();
char c;
int strlen = strs[0].length();
for (int i = 0; i < strlen; i++) {
c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
//如果超出字符串的长度或者与候选值不同,则直接返回
if (i >= strs[j].length() || c != strs[j].charAt(i)) {
return sb.toString();
}
}
sb.append(c);
}
return sb.toString();
}
}