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: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
自己写的时候总是各种边界条件没有检查到.
这个思路还不错,并不是采用取出第i个字符,然后逐一比较, 直接把第一个字符串的长度作为循环条件
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.empty())return string(); string res; for(int i=0;i<strs[0].size();++i) { int j=1; for(;j<strs.size()&&strs[j].size()>i;++j) if(strs[j][i]!=strs[0][i]) return res; if(j==strs.size()) res+=strs[0][i]; } return res; } };