编写一个函数来查找字符串数组中的最长公共前缀,保证存在。C++
时间: 2024-05-27 09:14:22 浏览: 18
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) { // 如果字符串数组为空,返回空字符串
return "";
}
char* prefix = strs[0]; // 初始化前缀为第一个字符串
for (int i = 1; i < strsSize; i++) {
int j = 0;
while (prefix[j] != '\0' && strs[i][j] != '\0' && prefix[j] == strs[i][j]) {
j++; // 找到最长公共前缀的长度
}
prefix[j] = '\0'; // 将前缀字符串的第一个不一致的字符设为字符串结束符
}
return prefix;
}
相关问题
编写一个函数来查找字符串数组中的最长公共前缀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;
}
编写一个函数来查找字符串数组中的最长公共前缀
```python
def longestCommonPrefix(strs):
if not strs:
return ""
if len(strs) == 1:
return strs[0]
strs.sort()
first = strs[0]
last = strs[-1]
for i, char in enumerate(first):
if char != last[i]:
return first[:i]
return first
```
这是一个查找字符串数组中最长公共前缀的函数。先判断字符串数组是否为空,如果为空则返回空字符串。如果只有一个字符串,则直接返回该字符串。将字符串数组按字典序排序,将第一个字符串和最后一个字符串取出来进行比较,找到最长公共前缀并返回。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.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)