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, 力扣 ...
随机推荐
- Android线程间异步通信机制源码分析
本文首先从整体架构分析了Android整个线程间消息传递机制,然后从源码角度介绍了各个组件的作用和完成的任务.文中并未对基础概念进行介绍,关于threadLacal和垃圾回收等等机制请自行研究. 基础 ...
- 【Oracle】闪回drop后的表
本文介绍的闪回方式只适用于:删除表的表空间非system,drop语句中没有purge关键字(以上两种情况的误删除操作只能通过日志找回): 1.删除表后直接从回收站闪回 SCOTT@LGR> d ...
- 基于物品的协同过滤ItemCF的mapreduce实现
文章的UML图比较好看..... 原文链接:www.cnblogs.com/anny-1980/articles/3519555.html 基于物品的协同过滤ItemCF 数据集字段: 1. Use ...
- nodeJs配置相关以及JSON.parse
nodeJs配置相关 实际上说应用相关更好吧,我不是很懂. 今天在工作中,被同事解决了一个问题,虽然多花了一些额外时间,但长痛不如短痛嘛 实际上的问题就是npm run target等命令可以,但是n ...
- (转) RabbitMQ学习之helloword(java)
http://blog.csdn.net/zhu_tianwei/article/details/40835555 amqp-client:http://www.rabbitmq.com/java-c ...
- Java中成员变量和局部变量区别
在类中的位置不同 重点 成员变量:类中,方法外 局部变量:方法中或者方法声明上(形式参数) 作用范围不一样 重点 成员变量:类中 局部变量:方法中 初始化值的不同 重点 成员变量:有默认值 局部变量: ...
- vc++文本框的编辑
新建mfc应用程序,单文档,起名Text,先编译一下 首先要创建一个插入符,用CreateSolid 窗口的高度宽度,可以通过GetSystemMetrics()函数获取 视类是覆盖在框架类之上的 创 ...
- python第六周:面向对象编程
面向对象编程: 世界万物,皆可分类 世界万物,对象 只要是对象,就肯定属于某种品类 只要是对象,就肯定有属性 oop编程利用"类"和"对象"来创建各种模型来实现 ...
- 【Codeforces Round #502 (in memory of Leopoldo Taravilse, Div. 1 + Div. 2) D】The Wu
[链接] 我是链接,点我呀:) [题意] 给你n个字符串放在multiset中. 这些字符串都是长度为m的01串. 然后给你q个询问 s,k 问你set中存在多少个字符串t 使得∑(t[i]==s[i ...
- RobotFrameWork+APPIUM实现对安卓APK的自动化测试----第六篇【AppiumLibrary等待函数介绍】
http://blog.csdn.net/deadgrape/article/details/50622441 废话不多说,少年们请看下面. Wait Until Page Contains text ...