Skip to content

Commit d65cd7a

Browse files
[N-0] refactor 14
1 parent 09c8742 commit d65cd7a

File tree

2 files changed

+51
-28
lines changed

2 files changed

+51
-28
lines changed
Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,42 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 14. Longest Common Prefix
5+
*
46
* Write a function to find the longest common prefix string amongst an array of strings.
57
*/
68

79
public class _14 {
810

9-
public static String longestCommonPrefix(String[] strs) {
10-
if (strs.length == 0) {
11-
return "";
12-
}
13-
14-
int i = 0;
15-
String prefix = "";
16-
String result = "";
17-
boolean broken = false;
18-
while (true) {
19-
i++;
20-
result = prefix;
21-
if (i > strs[0].length()) {
22-
break;//this will break out the while loop
11+
public static class Solution1 {
12+
public String longestCommonPrefix(String[] strs) {
13+
if (strs.length == 0) {
14+
return "";
2315
}
24-
prefix = strs[0].substring(0, i);
25-
for (String word : strs) {
26-
if (i > word.length() || !word.startsWith(prefix)) {
27-
broken = true;
28-
break;//this will only break out of the for loop
16+
17+
int i = 0;
18+
String prefix = "";
19+
String result = "";
20+
boolean broken = false;
21+
while (true) {
22+
i++;
23+
result = prefix;
24+
if (i > strs[0].length()) {
25+
break;//this will break out the while loop
26+
}
27+
prefix = strs[0].substring(0, i);
28+
for (String word : strs) {
29+
if (i > word.length() || !word.startsWith(prefix)) {
30+
broken = true;
31+
break;//this will only break out of the for loop
32+
}
33+
}
34+
if (broken) {
35+
break;//this will break out the while loop
2936
}
3037
}
31-
if (broken) {
32-
break;//this will break out the while loop
33-
}
38+
return result;
3439
}
35-
return result;
3640
}
3741

38-
public static void main(String... strings) {
39-
// String[] strs = new String[]{"a"};
40-
String[] strs = new String[]{"a", "b"};
41-
System.out.println(longestCommonPrefix(strs));
42-
}
4342
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._14;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _14Test {
10+
private static _14.Solution1 solution1;
11+
private static String[] strs;
12+
13+
@BeforeClass
14+
public static void setup() {
15+
solution1 = new _14.Solution1();
16+
}
17+
18+
@Test
19+
public void test1() {
20+
strs = new String[]{"a", "b"};
21+
assertEquals("", solution1.longestCommonPrefix(strs));
22+
}
23+
24+
}

0 commit comments

Comments
 (0)