[leetcode] 第一周作业
程序员文章站
2022-07-14 17:43:19
...
题目来源: 14. Longest Common Prefix
题目
Write a function to find the longest common prefix string amongst an array of strings.
分析:
比较直白的思路:
初始化公共前缀就是第一个字符串,然后和后面的每一个字符串比较,寻找与公共前缀中相等的前缀长度
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int num_of_str = strs.size();
if (num_of_str == 0) return "";
if (num_of_str == 1) return strs[0];
int first_str_length= strs[0].size();
string result= "";
for (int i= 0; i< first_str_length; i++) {
for (int j= 1; j< num_of_str; j++) {
if (strs[j][i] != strs[0][i] || i>= strs[j].size()) {
return result;
} else {
if (j == num_of_str-1) result+= strs[0][i];
}
}
}
return result;
}
};