Longest Common Prefix Problem
Description
LeetCode Problem 14.
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 lower-case English letters.
Sample C++ Code
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) {
if (strs.size() == 0)
return "";
string prefix = strs[0];
int p = strs[0].size();
int i, j;
for (i = 0; i < strs.size(); i ++) {
for (j = 0; j < p; j ++) {
if (prefix[j] != strs[i][j])
break;
}
p = j;
prefix = prefix.substr(0, p);
}
return prefix;
}
};