您的位置:首页 > 其它

[LeetCode] Longest Common Prefix

2015-07-12 13:57 375 查看
Use the strs[0] as the reference string and then compare it with the remaining strings from left to right. Once we find a string with length less than strs[0] or different letters in the corresponding position, we cannot move on and should return the longest common prefix string lcp. Each time we finish checking a position and have not returned, we add the letter at that position to lcp.

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