题目地址:https://leetcode.com/problems/longest-common-prefix/
思路:先遍历一遍,确定最小的字符串长度;然后设计2层循环,外层是最小长度,内层遍历每个字符串。依次看看每个字符串的第0、1、2...个字符是否相等。注意字符数组为空的特殊情况。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int min_len = INT_MAX; // 单个字符串最小长度
for (int i=0; i<strs.size(); i++) {
if (strs[i].length() < min_len) {
min_len = strs[i].length();
}
}
// cout << min_len << endl;
if (min_len == INT_MAX) {
return "";
}
vector<char> result;
for (int j=0; j<min_len; j++) {
char ch = strs[0][j];
for (int i=0; i<strs.size(); i++) {
if (strs[i][j] == ch) {
//
} else {
string s(result.begin(), result.end());
return s;
}
}
result.push_back(ch);
}
string s(result.begin(), result.end());
return s;
}
};
Runtime | Memory |
---|---|
4ms | 8.9 MB |