Leetcode刷题记——14. Longest Common Prefix(最长公共前缀)
来源:互联网 发布:caffe经典模型实战pdf 编辑:程序博客网 时间:2024/05/01 15:08
一、题目叙述:
Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
二、解题思路:
非常简单的题,但我交了四次。。。说思路。
1、首先比较前两个字符串,从第一个字符挨个比较,相等加入公共前缀字符串变量,不相等跳出。
2、其余字符串数组的字符串挨个与第一步得到的字符串变量比较,从第一个字符挨个比较,不相等,减去不相等之后的部分。
注意:
a.注意考虑字符串数组为空即一个字符串也没有的情况
b.注意字符串数组只有一个字符串,那么最长的公共前缀就是这个字符串。
c.这是我自己写的时候的疏漏,当把第一步得到的公共前缀与后面的字符串比较时,若后面的字符串比前面得到的公共前缀还短,那么先把记录公共前缀的字符串裁剪的跟当前字符串数组的字符串长度相等,再比较。
三、源源源码:
public class Solution { public String longestCommonPrefix(String[] strs) { String a = ""; if (strs.length == 1) return strs[0]; if (strs.length == 0) return ""; for (int i = 0; i < Math.min(strs[0].length(), strs[1].length()); i++) { if (strs[0].charAt(i) == strs[1].charAt(i)) { a = a + strs[0].charAt(i) + ""; } else break; } for (int i = 2; i < strs.length; i ++) { if (strs[i].length() < a.length()) a = a.substring( 0, strs[i].length()); for (int j = 0; j < Math.min(strs[i].length(), a.length()); j ++) { if (strs[i].charAt(j) != a.charAt(j)) { // if (j == 0) return ""; a = a.substring(0, j); break; } } } return a; } public static void main(String args[]) { String[] tr = new String[3]; tr[0] = "a"; tr[1] = "a"; tr[2] = ""; Solution a = new Solution(); System.out.println(a.longestCommonPrefix(tr)); }}
0 0
- Leetcode刷题记——14. Longest Common Prefix(最长公共前缀)
- LeetCode 14. Longest Common Prefix(最长公共前缀)
- Leetcode#14. Longest Common Prefix (最长公共前缀字符串)
- Leetcode:Longest Common Prefix 最长公共前缀
- (LeetCode)Longest Common Prefix --- 最长公共前缀
- 【LeetCode】14. Longest Common Prefix 最长公共前缀问题
- LeetCode 14. Longest Common Prefix最长公共前缀
- LeetCode | 14. Longest Common Prefix(最长公共前缀)
- LeetCode.14. Longest Common Prefix(最长公共前缀)
- leetcode 14. Longest Common Prefix 最长公共前缀
- leetcode——Longest Common Prefix 最长公共前缀(AC)
- LeetCode | Longest Common Prefix(最长公共前缀)
- LeetCode OJ 之 Longest Common Prefix (最长公共前缀)
- [C++]LeetCode 14: Longest Common Prefix(最长公共前缀)
- LeetCode:最长公共前缀(Longest Common Prefix)
- LeetCode 第十四题 Longest Common Prefix(最长公共前缀)
- LeetCode 14 Longest Common Prefix(最长公共前缀)
- Longest Common Prefix(最长公共前缀)
- 工作记录之Spring学习笔记(1)集合的注入
- git实战1
- 珠海空号检测的运行原理
- jQuery源码解析之构造函数的方法
- Servlet3.0 新特性之模块化实践
- Leetcode刷题记——14. Longest Common Prefix(最长公共前缀)
- hive函数 -- split 字符串分割函数
- php 匹配中文 字母下划线
- 主流浏览器内核介绍
- window.location.search.substr(一).split(\"&\")代表什么意思
- jQuery源码解析之自调用匿名函数
- 运维笔记8(网关,DNS,DHCP)
- DrawerLayout的学习
- 仿淘宝物流效果(物流时间轴效果)