Leetcode_Easy_14
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0)
return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++){
while (strs[i].indexOf(prefix) != 0){
prefix = prefix.substring(0, prefix.length()-1);
if (prefix.isEmpty())
return "";
} }
return prefix;
}
}
知识点1:
方法:String.indexOf(String)
while (strs[i]. indexOf(prefix) != 0) {...}
这个循环用来比较两个字符串,直到找到完全相同的前缀(因为prefix永远从0,末尾长度-1)
如果两个字符串不一样,比如String a = "letter"; String b = "love", 那么 a.indexOf(b) = -1; 返回值是int -1。
如果两个字符串相同,返回值就是0.
如果 String a = "letter"; a.indexOf('t') --> 返回值是2(第一次出现的位置)
知识点2:
int[] arr = new int[3];
System.out.println(arr.length);//数组长度 String str = "abc";
System.out.println(str.length());//字符串长度
数字: Array.length 是属性,不加括号!!!
字符串:String.length() 是方法,加括号!!!
Leetcode_Easy_14的更多相关文章
随机推荐
- qt之qmake
qt之qmake qmake 10分钟学会使用qmake 创建一个项目文件 qmake使用储存在项目(.pro)文件中的信息来决定Makefile文件中该生成什么. 一个基本的项目文件包含关于应用程序 ...
- dalaozouleyeyaojianqiangdehuoxiaqu
dalaozouleyeyaojianqiangdehuoxiaqu 没错,YY又开始哔哔了,非常不淡定,发个博客冷静一下反正没人看 好吧他们还是退役了,关键是我昨天竟然没看到博文???? (我是不会 ...
- python-数据分析与展示(Numpy、matplotlib、pandas)---2
笔记内容整理自mooc上北京理工大学嵩天老师python系列课程数据分析与展示,本人小白一枚,如有不对,多加指正 1.python自带的图像库PIL 1.1常用API Image.open() ...
- 关于Eclipse新建Dynamic Web Projecj默认未创建web.xml的问题
当使用eclipse新建Dynamic Web Projecj时,由于J2EE技术规范的更新,当使用Dynamic web module version默认版本为3.0时,将默认不会创建web.xml ...
- 开启redis-server提示 # Creating Server TCP listening socket *:6379: bind: Address already in use--解决方法
在bin目录中开启Redis服务器,完整提示如下: 3496:C 25 Apr 00:56:48.717 # Warning: no config file specified, using the ...
- 【题解】luogu P3386 【模板】二分图匹配
题面:https://www.luogu.org/problemnew/show/P3386 好像没有人发Ford-Fulkerson,我来一发, 这道题和P2756飞行员配对方案问题方法一样,网络流 ...
- VIM自动补全Python代码
pydiction插件 https://codeload.github.com/rkulla/pydiction/zip/master 新建bundle文件夹 mkdir ~/.vim/bundle ...
- python简说(二)list
一.list # 1.list 列表 数组a = ['A', 'B', 'C', 'D']# 0 1 2# 2.空list# a = []# a = list()# 3.下标 角标 索引# print ...
- 牛客练习赛24题解(搜索,DP)
A题,C题不讲,基础题(但是我要抨击一下这次比赛,卡cin,cout,卡的太狠了,根本就不让过的那种,QAQ) 链接:https://www.nowcoder.com/acm/contest/157/ ...
- topcoder srm 485 div1
problem1 link 枚举第一个数和第二个数即可确定公差. problem2 link 设高度为$n$,宽度为$m$,且$n \ge m$ 如果$m \ge 5$,那么答案为0.这个可以通过抽屉 ...