Longest Common Prefix
Problem
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 ""
.
Constraints
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters.
Solution
The problem Longest Common Prefix
can be solved using a vertical scanning technique through all given strings.
Implementation
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
for (int i = 0; i < strs[0].length(); i++)
for (int j = 1; j < strs.size(); j++)
if (i == strs[j].length() || strs[0][i] != strs[j][i])
return strs[0].substr(0, i);
return strs[0];
}
};