14. Longest Common Prefix
Description
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:
1 2
| Input: strs = ["flower","flow","flight"] Output: "fl"
|
Example 2:
1 2 3
| Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
|
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters if it is non-empty.
Hints/Notes
Solution
Language: C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: string longestCommonPrefix(vector<string>& strs) { int res = INT_MAX; for (int i = 0; i < strs.size() - 1; i++) { res = min({res, (int)strs[i].size(), (int)strs[i + 1].size()}); for (int j = 0; j < res; j++) { if (strs[i][j] != strs[i + 1][j]) { res = j; break; } } if (!res) { return ""; } } return strs[0].substr(0, res); } };
|
Another solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: string longestCommonPrefix(vector<string>& strs) { int j; for (j = 0; j < strs[0].size(); j++) { for (auto& str : strs) { if (j == str.size() || strs[0][j] != str[j]) { return strs[0].substr(0, j); } } } return strs[0]; } };
|