Skip to content

Commit 81cff62

Browse files
EASY/src/easy/LongestCommonPrefix.java
1 parent bb2b2e1 commit 81cff62

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package easy;
2+
3+
public class LongestCommonPrefix {
4+
5+
public static String longestCommonPrefix(String[] strs) {
6+
if(strs.length == 0) return "";
7+
8+
int i = 0;
9+
String prefix = "";
10+
String result = "";
11+
boolean broken = false;
12+
while(true){
13+
i++;
14+
result = prefix;
15+
if(i > strs[0].length()) break;//this will break out the while loop
16+
prefix = strs[0].substring(0, i);
17+
for(String word : strs){
18+
if(i > word.length() || !word.startsWith(prefix)) {
19+
broken = true;
20+
break;//this will only break out of the for loop
21+
}
22+
}
23+
if(broken) break;//this will break out the while loop
24+
}
25+
return result;
26+
}
27+
28+
public static void main(String...strings){
29+
// String[] strs = new String[]{"a"};
30+
String[] strs = new String[]{"a", "b"};
31+
System.out.println(longestCommonPrefix(strs));
32+
}
33+
}

0 commit comments

Comments
 (0)