LeetCode第14题,难度简单。将近两年以前做的题目了,回头看说不定会有新的做题思路。
原题地址:https://leetcode-cn.com/problems/longest-common-prefix/)
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
同时,给的字符串输入中只包含小写字母。
解题思路:
先说一下我的代码是怎么样的,再说下我写的时候想到的其他的解法。
我的代码:
优化的点:
中文官网题解:
https://leetcode-cn.com/problems/longest-common-prefix/solution/
个人题解:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
} else if (strs.length == 1) {
return strs[0];
}
String commonPrefix = "";
int length = strs[0].length();
for (String str : strs) {
if (str.length() < length) {
length = str.length();
}
}
for (int i = 0; i < length; i++) {
char c = strs[0].charAt(i);
for (String str : strs) {
if (str.charAt(i) != c) {
return commonPrefix;
}
}
commonPrefix += c;
}
return commonPrefix;
}
}
结果:
可能就是多了那步循环,所以速度慢了一倍?