
一、14.最⻓公共前缀
题目链接:14.最⻓公共前缀
题目描述:
解题思路:
- 思路一:
-
- 我们直接两两求一下公共前缀,记录在ret字符串中,然后ret与后续继续求公共前缀,最后的ret就是结果
-
- 求公共前缀,我们就求一下在字符串中的公共前缀的最后一个字符 的下一个下标即可。
- 思路二:
-
- 我们就将第一个字符串作为基准,遍历字符串,每个字符再与字符串数组中剩下的字符串,对应下标的字符比较即可。
-
- 当超出某个字符串长度或者字符不同了,就可以返回了。
-
- 最后第一个字符串都遍历完了,还没找到,那么第一个字符串就是结果。
解题代码:
思路一:
//时间复杂度: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;
}
//返回两个字符串的公共前缀
public 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 = 0; i < strs[0].length(); i