-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Common Prefix.java
58 lines (31 loc) · 1.23 KB
/
Longest Common Prefix.java
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
56
57
58
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
//pointer iterate on each word separately
for (int i = 0; i < strs[0].length() ; i++){
char c = strs[0].charAt(i);
//iterate on all the array
for (int j = 1; j < strs.length; j ++) {
//the second condition for not see the "
if (i == strs[j].length() || strs[j].charAt(i) != c)
return strs[0].substring(0, i);
}
}
return strs[0];
}
}
#AnotherSolution
class Solution {
public String longestCommonPrefix(String[] strs) {
Arrays.sort(strs);
StringBuilder result=new StringBuilder();
char[] first=strs[0].toCharArray();
char[] last=strs[strs.length-1].toCharArray();
for(int i=0;i<first.length;i++){
if(first[i]!=last[i]){
break;}
result.append(first[i]);
}
return result.toString();
}
}