您的位置:首页 > 其它

LeetCode-Longest Common Prefix

2014-08-18 14:31 246 查看
Write a function to find the longest common prefix string amongst an array of strings.

Solution:

Code:

<span style="font-size:14px;">class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
const int lengthV = strs.size();
if (lengthV == 0) return "";
if (lengthV == 1) return strs[0];
bool dismatch;
const int length = strs[0].size();
for (int i = 0; i < length; ++i) {
dismatch = false;
for (int j = 1; j < lengthV; ++j)
if (strs[j][i] != strs[0][i]) {
dismatch = true;
break;
}
if (dismatch)
return strs[0].substr(0, i);
}
return strs[0];
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息