每日一题:最长公共前缀
![3b0d8fd7a0f8ef0bc1fe0993575d8c35.png](https://img-blog.csdnimg.cn/img_convert/3b0d8fd7a0f8ef0bc1fe0993575d8c35.png)
开始
这题比昨天的罗马数字我感觉难度差不多
但是写起来却繁琐了一些,不那么有美感
class Solution {
public static String longestCommonPrefix(String[] strs) {
int strsLen = strs.length;
if (strsLen == 0) { return ""; }
char[][] css = new char[strsLen][200];
for (int i = 0; i String s = strs[i];
for (int j = 0; j css[i][j] = s.charAt(j);
}
}
char[] cs = new char[200];
for (int i = 0; i 100; i++) {
char target = css[0][i];
boolean allSame = true;
for (int j = 0; j char curr = css[j][i];
if (curr == target) {
continue;
}
allSame = false;
}
if (allSame) {
cs[i] = target;
} else {
return c2s(cs);
}
}
return c2s(cs);
}
private static String c2s(char[] cs) {
StringBuilder sb = new StringBuilder();
for (char c : cs) {
if (c != '\u0000') {
sb.append(c);
continue;
}
return sb.toString();
}
return sb.toString();
}
}
大体思路是分两个步骤
第一步:把输入用二维字符数组存储
第二步:从横向遍历转为纵向遍历
那么就可以把字符一个个拉出来比较异同了,直到发现不同就return了
这里学到个新知识
原来char的初始值是'\u0000',开始没处理,执行一直无法通过,后来只好祭出StringBuilder拼接大法了
老规矩,秀一下效率哈哈~
![39f6284ff7c9ea26a0c6e94e37fcd0d9.png](https://img-blog.csdnimg.cn/img_convert/39f6284ff7c9ea26a0c6e94e37fcd0d9.png)
这次还是比较满意der~