14. Longest Common Prefix[E]最长公共前缀
题目
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 "".
Example1:
Input:["flower","flow","flight"]
Output:"fl"
Example2:
Input:["dog","racecar","car"]
Output:""
Explanation: There is no common prefix among the input strings.
思路
思路一:暴力搜索
本题思路很简单,需要找到最长公共前缀,那么就需要有一个字符串作为基准,在其他字符串中寻找公共字符串。我们以第一个字符串为基准在其他字符串中寻找。寻找的终止条件:
- 当前遍历的长度超过字符串长度
- 基准字符串的第i个字符与当前字符串第i个字符不匹配。
思路二:优化搜索
寻找题目的隐含条件。 需要找的是公共字符串,那么以长度字符串为基准一定能加快程序的速度。此外,我们考虑将字符串数组排序。字符串的排序是按照字母来的,这样做的好处是将公共字符比较多的字符串集中起来,而公共字符比较少的将被放在数组(vector)的两端。例如例1的输入数组["flower","flow","flight"],排序后为:["flight", "flow", "flower"]。我们将第一个与最后一个字符串对比,搜寻公共子串。为了防止溢出,以第一个与最后一个长度较短的为基准查找。
Tips
Vector(STL)
主要是vector容器的begin()、end()和front()、back()函数。
(1)begin()
返回当前vector容器中起始元素的迭代器。
//定义一个int容器的迭代器
vector<int>::iterator iter;
//声明并初始化一个int类型的容器
vector<int> vec={1, 2, 3, 4, 5};
iter = vec.begin();
//返回迭代器表示的元素内容
cout << *iter << endl; //结果为1
(2)end()
返回当前vector容器中末尾元素的迭代器。注意end()返回的是最后一位的下一位。
//定义一个int容器的迭代器
vector<int>::iterator iter;
//声明并初始化一个int类型的容器
vector<int> vec={1, 2, 3, 4, 5};
iter = vec.end() - 1; //end()指向最后一位的下一位
//返回迭代器表示的元素内容
cout << *iter << endl; //结果为5
(3)front()
返回当前vector容器中起始元素的引用。
//声明并初始化一个int类型的容器
vector<int> vec={1, 2, 3, 4, 5};
//返回迭代器表示的元素内容
cout << vec.front() << endl; //结果为1
(4)back()
返回当前vector容器中末尾元素的引用。
//声明并初始化一个int类型的容器
vector<int> vec={1, 2, 3, 4, 5};
//返回迭代器表示的元素内容
cout << vec.back() << endl; //结果为5
List(python)
python的列表(List)是序列类型,因此与字符串有一些共同特点,列表与字符串的不同主要在于
- 列表可以包含其他元素,而不仅包含字符。列表可以包含任何类型的元素序列,甚至可以包含不同类型元素混合的序列。
- 列表是可变类型。
(1)创建python列表
List1 = [1, 2, 3, 4, 5]
List2 = ['a', 'b', 'c', 'd', 'e']
List3 = [1, 2, 'a', 'b']
(2)函数
对于一个列表A
- len(A):返回列表A的长度,即元素个数。
- min(A):返回列表A中的最小元素。如果A是列表的列表,则只考虑每个列表的第一个元素。
- max(A):返回列表A中的最大元素。如果A是列表的列表,则只考虑每个列表的第一个元素。
- sum(A):返回列表A所有元素的和,A中元素必须是数字。
C++
- 思路1
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string s = "";
if(strs.size() == 0)
return "";
for(int i = 0; i < strs[0].length();i++) //以第一个元素为基准
{
char c = strs[0].at(i);
for(int j = 1;j < strs.size();j++)
{
if(i >= strs[j].length() || strs[j].at(i) != c)
return s;
}
s += c;
}
return s;
}
};
- 思路2
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty())
return "";
sort(strs.begin(), strs.end());
int i = 0;
int len = min(strs[0].size(), strs.back().size());
while (i < len && strs[0][i] == strs.back()[i])
i ++;
return strs[0].substr(0, i);
}
};
Python
- 思路2
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
if len(strs)==1:
return strs[0]
minStr = min(strs)
maxStr = max(strs)
result = ""
for i in range(len(minStr)):
if minStr[i] != maxStr[i]:
return minStr[:i]
return minStr
总结
写代码充分运用
- 公共(以长度最短字符串作为基准)
- 前缀(利用子字符串方法)
这两个关键字。
参考
[1] https://www.cnblogs.com/grandyang/p/4606926.html
14. Longest Common Prefix[E]最长公共前缀的更多相关文章
- LeetCode 14 Longest Common Prefix(最长公共前缀)
题目链接:https://leetcode.com/problems/longest-common-prefix/?tab=Description Problem: 找出给定的string数组中最 ...
- LeetCode OJ:Longest Common Prefix(最长公共前缀)
Write a function to find the longest common prefix string amongst an array of strings. 求很多string的公共前 ...
- 14. Longest Common Prefix【leetcode】
14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array ...
- [LeetCode][Python]14: Longest Common Prefix
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...
- Leetcode 14. Longest Common Prefix(水)
14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...
- leetCode练题——14. Longest Common Prefix
1.题目 14. Longest Common Prefix Write a function to find the longest common prefix string amongst a ...
- [LeetCode]14. Longest Common Prefix最长公共前缀
Write a function to find the longest common prefix string amongst an array of strings. If there is n ...
- Leetcode No.14 Longest Common Prefix最长公共前缀(c++实现)
1. 题目 1.1 英文题目 Write a function to find the longest common prefix string amongst an array of strings ...
- 【LeetCode】14. Longest Common Prefix 最长公共前缀
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:prefix, 公共前缀,题解,leetcode, 力扣 ...
随机推荐
- 使用新的CSS类型对象模型
el.attributeStyleMap.set('padding', CSS.px(42)); const padding = el.attributeStyleMap.get('padding') ...
- Amaze UI的一点总结
做一个微信公众号内的网页的时候,用到了Amaze UI,也称妹子UI. 官网上宣称,Amaze UI中国首个开源 HTML5 跨屏前端框架,用下来的感觉是比较类似于bootstrap,都是移动端优先. ...
- 如何把数值或者对象添加到ArrayList集合
生成6个1~33之间的随机整数,添加到集合,并遍历 public class ArrayListDemo1 { public static void main(String[] args) { // ...
- centos7常见的操作
centos7的网络IP地址配置文件在 /etc/sysconfig/network-scripts 文件夹下, 查看当前网卡名称 ip ad li ens33网卡对应的配置文件为ifcfg-ens ...
- 三维地图中的A*寻路
跟二维地图原理一样,只不过搜索方向多了,二维只搜8个方向,而三维要搜26个方向. 不懂的看我以前写的文章,这里直接贴代码: #include <iostream> #include < ...
- kernel对NTP的API,系统调用函数
kenrel API for NTP kernel 提供两个API(即系统调用 system call)给应用程序NTP,去校准kernel system clock Kernel Applicati ...
- sessionStorage与clone方法在项目中的应用
//资料列表: //JSON.parse(jsonstr); //json格式字符串转换成json对象 //JSON.stringify(jsonobj); //json对象转换成json格式字符串 ...
- HDU2149 - Public Sale【巴什博弈】
虽然不想,但是现实总归是现实,Lele始终没有逃过退学的命运,因为他没有拿到奖学金.现在等待他的,就是像FarmJohn一样的农田生涯. 要种田得有田才行,Lele听说街上正在举行一场别开生面的拍卖 ...
- OOA,OOD,OOP区别
定义: OOA(Object-Oriented Analysis,面向对象分析方法) OOD(Object-Oriented Design,面向对象设计) OOP(Object Oriented Pr ...
- PHP 中 call_user_func 的使用
call_user_func函数类似于一种特别的调用函数的方法,使用方法如下 第一种情况: function set_max($a,$b) { if($a>$b) echo $a; else e ...