编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
1String c = "aaa";
System.out.println(c.length()); //结果为3
String[] d = new String[2];
d[0]="1";d[1]="2";
d.length); //结果为2
length与length()都是求长度的属性。length是针对数组的函数,而length()是指字符的长度
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
int length = strs[0].length();
int count = strs.length;
for (int i = 0; i < length; i++) {
char c=strs[0].charAt(i);
for (int j=1;j<count;j++){
if (i==strs[j].length()||strs[j].charAt(i)!=c){
return strs[0].substring(0,i);//直到不等的时候,使用substring进行截取子字符串
}
}
}
return strs[0];
}
//length与length()都是求长度的属性。length是针对数组的函数,而length()是指字符的长度
//substring的用法https://www.runoob.com/java/java-string-substring.html
实现调用:
package com.kk;
import java.util.Scanner;
public class LongestCommonPrefix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] strs = new String[3];
for (int j = 0; j < strs.length; j++) {
strs[j]=String.valueOf(scanner.next());
}
longestCommonPrefix(strs);
System.out.println(longestCommonPrefix(strs));
/* String []strings={"adsf","adfg","adrf"};
String s=longestCommonPrefix(strings);
System.out.println(s);*/
}
public static String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
int length = strs[0].length();
int count = strs.length;
for (int i = 0; i < length; i++) {
char c=strs[0].charAt(i);
for (int j=1;j<count;j++){
if (i==strs[j].length()||strs[j].charAt(i)!=c){
return strs[0].substring(0,i);//直到不等的时候,使用substring进行截取子字符串
}
}
}
return strs[0];
}
}
//length与length()都是求长度的属性。length是针对数组的函数,而length()是指字符的长度
//substring的用法https://www.runoob.com/java/java-string-substring.html