題目: LeetCode - 14. Longest Common Prefix

題目說明

給一個陣列,裡面的元素為 String,求此陣列中所有元素最長的相同開頭字串。

解題思路

使用第一個元素去比對即可,若是碰到不符合的就直接回傳子串。若是都符合代表最長的就是 strs[0]

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// fast IO
static auto __ = []()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
int n = strs.size(), N = strs[0].size();
for(int i = 0; i < N; ++i)
for(int j = 1; j < n; ++j)
if(strs[j][i] != strs[0][i])
return strs[0].substr(0, i);
return strs[0];
}
};