Longest Common Prefix
来源:互联网 发布:索尼网络签约经销商 编辑:程序博客网 时间:2024/03/28 19:06
Leetcode 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
题目要求在字符串数组中找到最前面的公共子串。题目本身语义不清,引用diss中的解释(粗体部分)方便理解。
For example:
{"a","a","b"} should give "" as there is nothing common in all the 3 strings.
{"a", "a"} should give "a" as a is longest common prefix in all the strings.
{"abca", "abc"} as abc
{"ac", "ac", "a", "a"} as a.
最正常的思路是将数组中第一个字符串的字符与其他字符串的字符作比较,因此需要两重循环,第一重循环循环的是第一个字符串的字符,第二个循环循环的是数组中的字符串,当出现字符不匹配时返回当前的公共子串;若在数组中均可匹配则字符后移。
代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string pre = "";
if (strs.size() == 0)
return pre;
int min = INT_MAX;
for (auto &s:strs)
min = (s.length() < min) ? s.length() : min;
for (int i = 0; i < min; i++)
{
char temp = strs[0][i];
for (auto &s:strs)
{
if (s[i] != temp)
{
return pre;
}
}
pre += temp;
}
return pre;
}
};
阅读全文
0 0
- LeetCode: Longest Common Prefix
- LeetCode Longest Common Prefix
- LeetCode : Longest Common Prefix
- [Leetcode] Longest Common Prefix
- leetcode6:Longest Common Prefix
- leetcode22: longest common prefix
- [LeetCode] Longest Common Prefix
- Leetcode14: Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- [LeetCode]Longest Common Prefix
- Longest Common Prefix
- LeetCode-Longest Common Prefix
- Longest Common Prefix
- [LeetCode] Longest Common Prefix
- Longest Common Prefix
- LeetCode - Longest Common Prefix
- 动态语言
- OpenSSL是什么?
- Jensen不等式证明过程
- 鸟哥的私房菜基础篇读书笔记
- JavaBean 属性copy
- Longest Common Prefix
- Linux(CentOS 7)安装Oracle 11g
- Oracle 11g完整安装(从下载到安装到基本命令使用)
- 达人篇:3.3)六西格玛
- Android8.0有关行为变更小结
- hdu3746—Cyclic Nacklace(kmp周期性质)
- 线段树的应用
- openssl pem 生成公钥和私钥及文件
- Java中的volatile关键字详解及单例模式双检锁问题分析