编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"] 输出: "fl"
示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
int index = 0;
char temp;
if(strs.size() == 0)
return ans;
while(1){
for(int i = 0; i < strs.size(); i++){
if(i == 0)
temp = strs[i][index];
if(index == strs[i].size() || strs[i][index] != temp)
return ans;
}
ans += temp;
index++;
}
}
};
博客主要围绕编写函数查找字符串数组中的最长公共前缀展开,若不存在则返回空字符串,还提及输入仅包含小写字母。
510

被折叠的 条评论
为什么被折叠?



