您的位置:首页 > 其它

[leetcode] 14. Longest Common Prefix

2015-12-07 16:08 411 查看
Write a function to find the longest common prefix string amongst an array of strings.

这道题是找出所有字符串的公共前缀,题目难度为easy。

题目比较简单就直接上代码了:class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
int pos = strs[0].size();
for(int i=1; i<strs.size(); i++) {
pos = min(pos, (int)strs[i].size());
for(int j=0; j<pos; j++) {
if(strs[0][j] != strs[i][j]) {
pos = j;
break;
}
}
}
return strs[0].substr(0, pos);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode