您的位置:首页 > 其它

[leetcode] 14. Longest Common Prefix[leetcode] 14. Longest Common Prefix

2017-12-17 10:56 393 查看
题目链接:https://leetcode.com/problems/longest-common-prefix/

Write a function to find the longest common prefix string amongst an array of strings.

思路

每次子串长度加1,直到子串不相等即是最大公共前缀

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0) return "";
string ans;
for(int i = 0;i < strs[0].size();i++){
char c = strs[0][i];
for(auto ch: strs)
if(i == ch.size() || ch[i] != c) return ans;
ans += c;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: