Leetcode 14. 最长公共前缀
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
-
1 <= strs.length <= 200
-
0 <= strs[i].length <= 200
-
strs[i]
仅由小写英文字母组成
解答
纵向扫描。 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
char c=0;
for (int j=0;j<strs[0].size();j++){
for (int i=0;i<strs.size();i++){
if (c==0){
c=strs[i][j];
}
else{
try
{
if (c!=strs[i][j])
return ans;
}
catch(int)
{
return ans;
}
}
}
ans.push_back(c);
c=0;
}
return ans;
}
};
Complexity
- Time: \(O(mn)\)
- Space: \(O(mn)\)
题外话
试试try catch
,注意catch()
里面必须要加点东西,写个int
就行。