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:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i] consists of only lower-case English letters.Longest Common Prefix - LeetCode
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int res = 0;
int minlen = INT_MAX;
for(string str:strs)
{
minlen = min(minlen,(int)str.size());
}
int flag = 1;
for(int i=0;i<minlen;i++)
{
for(int j=0;j<strs.size()-1;j++)
{
if(strs[j][i]!=strs[j+1][i])
{
flag = 0;
break;
}
}
if(!flag)
break;
else
res++;
}
return strs[0].substr(0,res);
}
};