一、14. 最长公共前缀
题目链接:14. 最长公共前缀
解题思路
- 思路一:两两求公共前缀,记录在结果字符串中,继续与后续字符串比较。
- 思路二:以第一个字符串为基准,遍历其字符并与数组中其他字符串对应下标字符比较。若超出某字符串长度或字符不同则返回;若遍历完未找到差异,则第一个字符串即为结果。
解题代码
// 思路一:时间复杂度 O(m*n),空间复杂度 O(1)
class Solution {
public String longestCommonPrefix(String[] strs) {
// 两两比较
String ret = strs[0];
for (int i = 1; i < strs.length; i++) {
ret = commonPrefix(ret, strs[i]);
}
return ret;
}
// 返回两个字符串的公共前缀
private String commonPrefix(String s1, String s2) {
int last = 0;
while (last < s2.length() && last < s1.length() && s2.charAt(last) == s1.charAt(last)) {
last++;
}
return s1.substring(0, last);
}
}
// 思路二:时间复杂度 O(m*n),空间复杂度 O(1)
class Solution {
public String longestCommonPrefix(String[] strs) {
// 一起比较
for (int ; i < strs[].length(); i++) {
strs[].charAt(i);
( ; j < strs.length; j++) {
(i >= strs[j].length() || ch != strs[j].charAt(i)) {
strs[].substring(, i);
}
}
}
strs[];
}
}


