题目

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]最长公共前缀的更多相关文章

  1. LeetCode 14 Longest Common Prefix(最长公共前缀)

    题目链接:https://leetcode.com/problems/longest-common-prefix/?tab=Description   Problem: 找出给定的string数组中最 ...

  2. LeetCode OJ:Longest Common Prefix(最长公共前缀)

    Write a function to find the longest common prefix string amongst an array of strings. 求很多string的公共前 ...

  3. 14. Longest Common Prefix【leetcode】

    14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array ...

  4. [LeetCode][Python]14: Longest Common Prefix

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...

  5. Leetcode 14. Longest Common Prefix(水)

    14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...

  6. leetCode练题——14. Longest Common Prefix

    1.题目 14. Longest Common Prefix   Write a function to find the longest common prefix string amongst a ...

  7. [LeetCode]14. Longest Common Prefix最长公共前缀

    Write a function to find the longest common prefix string amongst an array of strings. If there is n ...

  8. 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 ...

  9. 【LeetCode】14. Longest Common Prefix 最长公共前缀

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:prefix, 公共前缀,题解,leetcode, 力扣 ...

随机推荐

  1. 前端面试基础-html篇之CSS3新特性

    CSS3的新特性(个人总结)如下 过度(transiton) 动画(animation) 形状转换 transform:适用于2D或3D转换的元素 transform-origin:转换元素的位置(围 ...

  2. win10下mysql安装过程中遇到的各种坑

    前几天重装系统,又要下回来mysql,但没想到还是遇到了许多麻烦,翻了十多篇博文才搞定,写个总结出来方便以后不要重复踩坑,也给大家参考参考. 1.下载与安装 这个没什么好说的,下载地址网上一大堆,安装 ...

  3. AngularJs轻松入门

    AngularJs轻松入门系列博文:http://blog.csdn.net/column/details/angular.html AngularJs轻松入门(一)创建第一个应用 AngularJs ...

  4. jQuery访问json文件

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. Fear No More歌词

      "Fear No More"   Every anxious thought that steals my breath It's a heavy weight upon my ...

  6. vc++实例

  7. appium不能获取webview内容的解决办法

    在用appium对小猿搜题app进行自动化测试时,准备用page_source打印出文章的xml内容 但是发现只能打印出外部结构内容,实际的文章内容却没有显示 截图如下 查询之后,得知需要通过cont ...

  8. Python笔记23------Python统计列表中的重复项出现的次数的方法

    https://www.cnblogs.com/hester/p/6197449.html

  9. 不能使用一般 Request 集合

    request.querystring("id"),不能request("id")

  10. windows远程桌面无法复制粘贴的解决方案

    方法一:在网上最常见的方法,就是杀掉 rdpclip.exe进程后重启. 在远程桌面的任务栏,右键启动任务管理器 这时候进程列表中已经没有看到rdpclip.exe了,桌面左下方点击[开始]--> ...