您的位置:首页 > 其它

14. Longest Common Prefix

2016-06-22 17:52 369 查看
Write a function to find the longest common prefix string amongst an array of strings

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
}
};


=========

题目:找vector中最长公共前缀,

思路:模拟比较的过程,我们可以看到这些.

按照数组中的第一个字符串开始进行比较,

对第一个字符串中的每一个字符,和其他字符串的相应位置进行比较,如果都相同那么将此字符加入到 待返回字符串中.

-------

string longestCommonPrefix(vector<string>& strs) {
string re;
if(strs.empty()) return re;
for(int i = 0;i<(int)strs[0].size();i++){
for(int j = 0;j<(int)strs.size();j++){
if(i>=(int)strs[j].size()) return re;
if(strs[j][i]==strs[0][i])
continue;
else
return re;
}
re.push_back(strs[0][i]);
}
return re;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: