编写一个函数来查找字符串数组中的最长公共前缀,保证存在。
时间: 2023-09-13 19:07:40 浏览: 50
以下是Python代码实现:
```
def longestCommonPrefix(strs):
if not strs:
return ""
prefix = strs[0]
for i in range(1, len(strs)):
while strs[i].find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
```
算法思路:
1. 先将第一个字符串设为前缀。
2. 从第二个字符串开始,若该字符串不是以前缀开头,则将前缀缩短一个字符,直到该字符串以前缀开头或前缀为空。
3. 重复步骤2,直到所有字符串都匹配完毕。
4. 返回前缀。
相关问题
编写一个函数来查找字符串数组中的最长公共前缀
```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
```
这是一个查找字符串数组中最长公共前缀的函数。先判断字符串数组是否为空,如果为空则返回空字符串。如果只有一个字符串,则直接返回该字符串。将字符串数组按字典序排序,将第一个字符串和最后一个字符串取出来进行比较,找到最长公共前缀并返回。
编写一个函数来查找字符串数组中的最长公共前缀。
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
示例:
输入: ["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);
}
};
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)