In the Leetcode Longest Common Prefix problem solution in C++ programming 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 “”.
Leetcode Longest Common Prefix problem solution in C++ programming
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n=strs.size();
string s="";
char r;
for(int i=0;i<strs[0].size();i++){
r=strs[0][i];
for(int j=1;j<n;j++){
if(i>=strs[j].size()||strs[j][i]!=r){
return s;
}
}
s+=r;
}
return s;
}
};
Also read,
- Leetcode Longest Common Prefix problem solution in C
- Leetcode Longest Common Prefix problem solution in Java
- Leetcode Longest Common Prefix problem solution in Python
- Leetcode Longest Common Prefix problem solution in C#