class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
}
};
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成原站题解
python3 解法, 执行用时: 44 ms, 内存消耗: 15.1 MB, 提交时间: 2022-08-26 15:54:55
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str 基本思路: 假设列表中第一个字符串最长, 然后依次与后边每一个字符串对比, 计算所有的最大匹配长度, 长度最小的就是 """ if len(strs) == 0: return "" str = strs[0] Min = len(str) for i in range(1, len(strs)): j = 0 p = strs[i] while j < Min and j < len(p) and p[j] == str[j]: j += 1 Min = Min if Min < j else j return str[:Min]
javascript 解法, 执行用时: 128 ms, 内存消耗: N/A, 提交时间: 2018-08-22 20:23:36
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { if ( strs.length == 0 ) return ""; var str = strs[0]; var Min = str.length; for ( var i = 1; i < strs.length; i++ ) { var s = strs[i]; var j = 0; while ( j < Min && j < s.length && s.substr(j, 1) == str.substr(j, 1) ) j++; Min = Min > j ? j : Min; } return strs[0].substring(0, Min); };
golang 解法, 执行用时: 4 ms, 内存消耗: N/A, 提交时间: 2018-08-22 20:18:59
func longestCommonPrefix(strs []string) string { if len(strs) == 0 { return "" } var str string = strs[0] var Min int = len(str) var s string var j int for i := 1; i < len(strs); i++ { j = 0 s = strs[i] for { if j < Min && j < len(s) && s[j:j+1] == str[j:j+1] { j++ continue } break } if Min > j { Min = j } } return strs[0][:Min] }
java 解法, 执行用时: 19 ms, 内存消耗: N/A, 提交时间: 2018-08-22 19:27:58
class Solution { public String longestCommonPrefix(String[] strs) { if ( strs.length == 0 ) return ""; char[] str = strs[0].toCharArray(); int Min = str.length; for ( int i = 1; i < strs.length; i++ ) { char[] s = strs[i].toCharArray(); int j = 0; while ( j < Min && j < s.length && s[j] == str[j] ) j++; Min = Min > j ? j : Min; } return strs[0].substring(0, Min); } }
c 解法, 执行用时: 4 ms, 内存消耗: N/A, 提交时间: 2018-08-22 19:26:21
char* longestCommonPrefix(char** strs, int strsSize) { char* str = strs[0]; int i, j; if ( strsSize == 0 ) return ""; for ( i = 1; i < strsSize; i++ ) { j = 0; while ( str[j] && strs[i][j] && str[j] == strs[i][j] ) j++; str[j] = 0; } return str; }
cpp 解法, 执行用时: 4 ms, 内存消耗: N/A, 提交时间: 2018-08-22 19:20:18
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if ( strs.size() == 0 ) return ""; char* str = (char*) malloc( sizeof (char)* (strs[0].size() + 1) ); for ( int i = 0; i < strs[0].size(); i++ ) { str[i] = strs[0][i]; } str[strs[0].size()] = 0; for ( int i=1; i<strs.size(); i++ ) { int j = 0; while ( str[j] && strs[i][j] && str[j] == strs[i][j] ) j++; str[j] = 0; } return string(str); } };