编写一个函数来查找字符串数组中的最长公共前缀。
时间: 2023-04-24 22:00:24 浏览: 111
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
示例:
输入: ["flower","flow","flight"]
输出: "fl"
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
思路:
先将字符串数组按照字典序排序,然后比较第一个字符串和最后一个字符串的公共前缀即可。
代码实现:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
sort(strs.begin(), strs.end());
string first = strs.front(), last = strs.back();
int i = ;
while(i < first.size() && first[i] == last[i]) i++;
return first.substr(, i);
}
};
相关问题
编写一个函数来查找字符串数组中的最长公共前缀c语言
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) { // 如果字符串数组为空,则返回空字符串
return "";
}
int len = strlen(strs[0]); // 获取第一个字符串的长度
for (int i = 0; i < len; i++) {
char ch = strs[0][i]; // 获取第一个字符串的第i个字符
for (int j = 1; j < strsSize; j++) { // 遍历其它字符串
if (i >= strlen(strs[j]) || strs[j][i] != ch) { // 如果其它字符串长度小于i或者第i个字符不同
strs[0][i] = '\0'; // 则将第一个字符串的第i个字符置为'\0'
return strs[0]; // 返回当前前缀
}
}
}
return strs[0]; // 返回第一个字符串,即为最长公共前缀
}
编写一个函数来查找字符串数组中的最长公共前缀c语言c++
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0)
return "";
char* prefix = strs[0];
int i, j;
for (i = 1; i < strsSize; i++) {
j = 0;
while (prefix[j] && strs[i][j] && prefix[j] == strs[i][j])
j++;
prefix[j] = '\0';
if (prefix[0] == '\0')
return "";
}
return prefix;
}
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)