您的位置:首页 > 其它

14. Longest Common Prefix

2016-03-22 23:38 260 查看
Write a function to find the longest common prefix string amongst an array of strings.

Subscribe to see which companies asked this question
求最长公共子串。
思路:可以把它想象成一个二维的字符数组,我们一列一列的遍历。
如果一列有一个数和第一行的字符不一样,那么就退出循环。
此时前面的字符部分就是最长子序列。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();
if(len==0)return "";
string ans=strs[0];
for(int i=1,j=0;i<len&&j<ans.size();i++){
string t=strs[i];
if(t[j]=='\0'){ans=t;break;}
if(ans[j]!=t[j]){
ans= ans.substr(0,j);
}
if(i==len-1){j++;i=0;}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: