-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Common_Prefix.java
More file actions
55 lines (44 loc) · 1.35 KB
/
Copy pathLongest_Common_Prefix.java
File metadata and controls
55 lines (44 loc) · 1.35 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
53
54
55
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array
of strings.
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0)
return "";
int index = 0;
while(index < strs[0].length()) {
for(int i=1; i<strs.length; ++i) {
if((index>=strs[i].length()) ||
(strs[i].charAt(index)!=strs[0].charAt(index)))
return strs[0].substring(0, index);
}
index++;
}
return strs[0];
}
}
/////////////////////////////////////////////////////////////
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length==0) {
return "";
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<strs[0].length(); i++) {
boolean stop = false;
char c = strs[0].charAt(i);
for(int n=1; n<strs.length; n++) {
if(i>=strs[n].length() || strs[n].charAt(i)!=c) {
stop = true;
break;
}
}
if(stop) {
break;
} else {
sb.append(c);
}
}
return sb.toString();
}
}