没有合适的资源?快使用搜索试试~ 我知道了~
LeetCode Longest Common Prefix解决方案
需积分: 0 0 下载量 92 浏览量
2024-01-23
23:10:42
上传
评论
收藏 11KB DOCX 举报
温馨提示
试读
1页
LeetCode Longest Common Prefix解决方案
资源推荐
资源详情
资源评论
Summary:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Solution:
~~~
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) {
return "";
}
int length = strs[0].length();
string temp = strs[0];
string result;
for (int i = 0; i < strs.size(); ++i) {
result = "";
if (strs[i].length() < length) {
length = strs[i].length();
}
for (int j = 0; j < length; ++j) {
if (temp[j] != strs[i][j]) {
break;
}
result += temp[j];
}
temp = result;
length = temp.length();
}
return result;
}
~~~
资源评论
句号(在IT行业摸爬滚打)
- 粉丝: 278
- 资源: 28
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功