LeetCode: 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
大意就是,写一个函数可以找到一个数组字符串中的最长前缀。
分析: 最长前缀的最大值为数组字符串中长度最短的字符,由最短字符串由后向前递减可以得到最长前缀。
算法构架:先遍历求得最短字符串和长度n,然后再次遍历数组,用最短字符串依次对比当前字符串前n个字符是否相等,不相等则n--,直到找到最短字符串和当前字符串前n个字符相等,继续遍历。
注意:因为是求共有的前缀,所以前缀必定满足所有字符串,因此只用单次遍历数组即可以求得答案。
public class Solution {public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0){return "";}int length = strs[0].length();String res = strs[0];for (int i = 1; i < strs.length; i++){if (strs[i].length() < length){length = strs[i].length();res = strs[i];}}for (String s : strs){while (!res.equals(s.substring(0,length))){length--;res = res.substring(0,length);}}return res;} }
复杂度为n
转载于:https://www.cnblogs.com/snakech/p/5758020.html
LeetCode: 14. Longest Common Prefix相关推荐
- 【easy!】LeetCode 14. Longest Common Prefix
LeetCode 14. Longest Common Prefix Solution1: 用的暴力遍历,时间复杂度O(n2)O(n2)O(n^2) class Solution { public:s ...
- LeetCode 14. Longest Common Prefix字典树 trie树 学习之 公共前缀字符串
所有字符串的公共前缀最长字符串 特点:(1)公共所有字符串前缀 (好像跟没说一样...) (2)在字典树中特点:任意从根节点触发遇见第一个分支为止的字符集合即为目标串 参考问题:https://lee ...
- LeetCode:14. Longest Common Prefix
两年硕士超快的鸭,又要准备秋招啦!0508第一题~ 题目 Write a function to find the longest common prefix string amongst an ar ...
- LeetCode 14. Longest Common Prefix
题意:给出n个字符串,求其公共子串 思路:两两求子串,LCP(S1,S2,....) = LCP(S1, LCP(S2,....)) 代码 如下: func longestCommonPrefix(s ...
- LeetCode - Easy - 14. Longest Common Prefix
Topic String Description https://leetcode.com/problems/longest-common-prefix/ Write a function to fi ...
- leetcode python3 简单题14. Longest Common Prefix
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第十四题 (1)题目 英文: Write a function to find th ...
- LeetCode之Longest Common Prefix
1.题目 Write a function to find the longest common prefix string amongst an array of strings 2.代码实现 pa ...
- Leet Code OJ 14. Longest Common Prefix [Difficulty: Easy]
题目: Write a function to find the longest common prefix string amongst an array of strings. 翻译: 写一个函数 ...
- 14. Longest Common Prefix
Title 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". Solve 1.横向扫描 用LCP(S1 -Sn)表示字符串S1 -Sn的最长 ...
最新文章
- python统计元素个数_python怎么统计列表中元素的个数
- MySQL count sum 条件查询
- mysql关于访问权限以及root密码修改
- MapReduce基础开发之九JDBC连接Hive
- POJ3041Asteroids(二分图最少顶点覆盖)
- 20220211-CTF-MISC-006-pure_color(stegsolve工具的使用)-007-Aesop_secret(AES解密)
- 关于'java' 不是内部或外部命令,也不是可运行的程序 或批处理文件 和 错误: 找不到或无法加载主类 helloworld的问题...
- 面向对象之编写一个完整的类
- mysql ip to int_ip网段转换程序(把ip地址转换成相对就的整数)
- OJ1065: 统计数字字符的个数(C语言)
- 经过这几年的磨练_通过构建这15个项目来磨练您JavaScript技能
- 【转】Jmeter + DadBoby 安装使用
- mysql5.1安装过程_MySQL 5.1.7安装全过程
- asp怎么循环增加字段和字段对应的值_索引该怎么创建?
- LPDDR4协议规范之 (四)命令和时序
- 解决天正M_批打印没有天正的打印格式(TArch20V6.ctb)的问题
- 能源物联网及其关键技术
- NLP实现文本分词+在线词云实现工具
- Dilated conv扩张卷积的理解(一看就会)
- 梳妆台行业调研报告 - 市场现状分析与发展前景预测