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的更多相关文章
随机推荐
- Properties (25)
1.Properties 没有泛型.也是哈希表集合,无序集合.{a=1,b=2,c=3} 2. 读取文件中的数据,并保存到集合 (Properties方法:stringPropertyName ...
- spring 事物的一些理解
推荐一个我认为Spring事物写得很好的文章. 文章链接:http://www.codeceo.com/article/spring-transactions.html 文章作者:码农网 – 吴极心 ...
- 【JavaScript 6连载】三、构造函数
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- linux 开始
3306 -- mysql 8000--django默认 服务由端口控制 https -- 443 http -- 80 linux发行版:1.centos 免费版的redhat2.ubuntu 乌版 ...
- vue组件通信之任意级组件之间的通信
<div id="app"> <comp1></comp1> <comp2></comp2> </div> ...
- python+selenium win32gui实现文件上传 enumerate()
upload = dr.find_element_by_id('exampleInputFile0') upload.click() time.sleep(1) # win32gui dialog = ...
- Eclipse导入MyEclipse创建的WEB项目无法识别的解决方案
Eclipse导入MyEclipse创建的WEB项目无法识别的解决方案
- Kattis之旅——Perfect Pth Powers
We say that x is a perfect square if, for some integer b, x = b2. Similarly, x is a perfect cube if, ...
- 使用准现网的数据,使用本地的样式脚本,本地调试准现网页面(PC适用)
原理: 本地逻辑,重新渲染 步骤: 1.安装插件:Tampermonkey 度盘:https://pan.baidu.com/s/1bpBVVT9 2.设置: 点击插件-->仪表盘 添加脚本 将 ...
- VIM编码检查
trouble shooting https://www.django.cn/article/show-4.html https://blog.csdn.net/lh756437907/article ...