14. Longest Common Prefix
Input: ["flower","flow","flight"]
Output: "fl"Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.algorithm thought
code
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==1)
return strs[0];
if(strs.size()==0)
return "";
string res="";
for(int i=0;i<strs[0].size();++i){
for(int j=1;j<strs.size();++j){
if(i==strs[j].size()||strs[0][i]!=strs[j][i]){
return res;
}
}
res.push_back(strs[0][i]);
}
return res;
}
};algorithm analysis
Last updated