leetcode笔记:Longest Common Prefix
发布时间:2020-12-13 21:05:21 所属栏目:PHP教程 来源:网络整理
导读:1. 题目描写 Write a function to find the longest common prefix string amongst an array of strings. 2. 题目分析 题目的大意是,给定1组字符串,找出所有字符串的最长公共前缀。 对照两个字符串的最长公共前缀,其前缀的长度肯定不会超过两个字符串中较
1. 题目描写 Write a function to find the longest common prefix string amongst an array of strings. 2. 题目分析 题目的大意是,给定1组字符串,找出所有字符串的最长公共前缀。 对照两个字符串的最长公共前缀,其前缀的长度肯定不会超过两个字符串中较短的长度,设最短的字符串长度为 使用变量 3. 示例代码 #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string> &strs)
{
if (strs.size() == 0)
return "";
string prefix = strs[0];
for (int i = 1; i < strs.size(); ++i)
{
if (prefix.length() == 0 || strs[i].length() == 0)
return "";
int len = prefix.length() < strs[i].length() ? prefix.length() : strs[i].length();
int j;
for (j = 0; j < len; ++j)
{
if (prefix[j] != strs[i][j])
break;
}
prefix = prefix.substr(0,j);
}
return prefix;
}
}; 4. 小结 该题思路不难,而且还有几种类似的解决思路,在实现时需要做到尽可能减少比较字符的操作次数。 版权声明:本文为博主原创文章,未经博主允许不得转载。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |