问题描述
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
这题的要求是输入一个字符串数组,给出所有字符串最长的相同开头子串。
解题思路
这题比较简单,直接暴力做就可以。
代码实现
public String longestCommonPrefix(String[] strs) {
int len = strs.length;
if(len == 0) return "";
int maxLen = strs[0].length();
for(int i = 0; i < maxLen; i++) {
char c = strs[0].charAt(i);
for(int j = 1; j < len; j++) {
//遇到结尾或者直接遇到不一样的字符就结束
if(i >= strs[j].length() || c != strs[j].charAt(i)) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
复杂度分析
时间复杂度是O(LN), L是最短的子串长度,N是输入的字符串数组中字符串数量
分析
昨天又偷懒,莫名其妙的又躺了一天。???不行啊小老弟