[Leetcode] Longest Common Prefix
Longest Common Prefix 题解
题目来源:https://leetcode.com/problems/longest-common-prefix/description/
Description
Write a function to find the longest common prefix string amongst an array of strings.
Solution
class Solution {
private:
size_t getShortestStrIdx(vector<string>& strs) {
size_t res = 0;
auto minLen = strs[0].length();
auto size = strs.size();
decltype(minLen) tempLen;
for (size_t i = 1; i < size; i++) {
tempLen = strs[i].length();
if (tempLen < minLen) {
minLen = tempLen;
res = i;
}
}
return res;
}
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty())
return "";
string res = strs[getShortestStrIdx(strs)];
auto size = strs.size();
for (size_t i = 0; i < size; i++) {
string::size_type len = 0;
while (len < res.length() && len < strs[i].length()) {
if (res[len] == strs[i][len])
len++;
else
break;
}
if (len == 0)
return "";
if (len < res.length())
res.resize(len);
}
return res;
}
};
解题描述
这道题题意是对给定的字符串数组,求所有字符串的最长公共前缀。我的算法是,先找到所有字符串中最短的一个,在用这个字符串作为结果初始值去跟其它所有字符串匹配。每次都从第0个字符开始,一旦第0个字符不匹配直接返回空串,反之则匹配到不匹配为止,每次刷新结果串的长度。