-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPerfix.java
More file actions
52 lines (50 loc) · 1.46 KB
/
Copy pathLongestPerfix.java
File metadata and controls
52 lines (50 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package AlgorithmTest;
/*
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
* */
public class LongestPerfix {
public static void main(String[] args) {
String [] aim ={
"a","a"
};
System.out.println(longest(aim));
}
public static String longest(String[] strs){
if(strs.length<=1){
if(strs.length==0){
return "";
}
return strs[0];
}
int result=-1;
if (strs[0].length()==0){
return "";
}
char temp=strs[0].toCharArray()[0]; //以第一个为参照物
boolean isRight=true;
while(isRight){
for (int j = 1; j <strs.length ; j++) {
if(strs[j].length()<=0){
return "";
}
if (result+1<strs[j].length()&&strs[j].toCharArray()[result+1]==temp){
continue;
}else{
isRight=false;
break;
}
}
if (isRight){
if (result+1>=strs[0].toCharArray().length){
return strs[0].substring(0,result+1);
}
result++;
temp=result+1<strs[0].length()?strs[0].toCharArray()[result+1]:' ';
}else{
break;
}
}
return strs[0].substring(0,result+1);
}
}