题目:
Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
int m = strs.size();
int n = INT_MAX;
for(int i = 0; i < m; i++) {
if(strs[i].size() < n)
n = strs[i].size();
}
if(m == 0 || n == 0)
return "";
string res;
for(int j = 0; j < n; j++) {
char ch = strs[0][j];
int flag = 1;
for(int i = 1; i < m; i++) {
if(strs[i][j] != ch) {
flag = 0;
break;
}
}
if(flag)
res.push_back(ch);
else
break;
}
return res;
}
};
本博客介绍了一个函数,用于找出给定字符串数组中最长的公共前缀字符串。通过遍历数组并比较字符串元素,实现高效查找过程。
286

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



