|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | /**
|
| 4 | + * 14. Longest Common Prefix |
| 5 | + * |
4 | 6 | * Write a function to find the longest common prefix string amongst an array of strings.
|
5 | 7 | */
|
6 | 8 |
|
7 | 9 | public class _14 {
|
8 | 10 |
|
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 ""; |
23 | 15 | }
|
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 |
29 | 36 | }
|
30 | 37 | }
|
31 |
| - if (broken) { |
32 |
| - break;//this will break out the while loop |
33 |
| - } |
| 38 | + return result; |
34 | 39 | }
|
35 |
| - return result; |
36 | 40 | }
|
37 | 41 |
|
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 |
| - } |
43 | 42 | }
|
0 commit comments