|
8 | 8 |
|
9 | 9 | public class _14 { |
10 | 10 |
|
11 | | - public static class Solution1 { |
12 | | - public String longestCommonPrefix(String[] strs) { |
13 | | - if (strs.length == 0) { |
14 | | - return ""; |
15 | | - } |
| 11 | + public static class Solution1 { |
| 12 | + public String longestCommonPrefix(String[] strs) { |
| 13 | + if (strs == null || strs.length == 0) { |
| 14 | + return ""; |
| 15 | + } |
| 16 | + if (strs.length == 1) { |
| 17 | + return strs[0]; |
| 18 | + } |
| 19 | + Character c; |
| 20 | + for (int i = 0;; i++) {// 可以增加i < strs[0].length()条件跳出循环,以防止程序错误时死循环 |
| 21 | + c = null; |
| 22 | + for (String str : strs) { |
| 23 | + if (str == null || str.length() < i + 1) { |
| 24 | + return str + ""; |
| 25 | + } |
| 26 | + if (c == null) { |
| 27 | + c = str.charAt(i); |
| 28 | + } else { |
| 29 | + if (!c.equals(str.charAt(i))) { |
| 30 | + return str.substring(0, i) + ""; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } |
16 | 37 |
|
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 |
36 | | - } |
37 | | - } |
38 | | - return result; |
39 | | - } |
40 | | - } |
41 | | - |
42 | | - public static class Solution2 { |
43 | | - //horizontal scan |
44 | | - public String longestCommonPrefix(String[] strs) { |
45 | | - if (strs.length == 0) { |
46 | | - return ""; |
47 | | - } |
48 | | - String prefix = strs[0]; |
49 | | - for (int i = 1; i < strs.length; i++) { |
50 | | - while (strs[i].indexOf(prefix) != 0) { |
51 | | - prefix = prefix.substring(0, prefix.length() - 1); |
52 | | - if (prefix.isEmpty()) { |
53 | | - return ""; |
54 | | - } |
55 | | - } |
56 | | - } |
57 | | - return prefix; |
58 | | - } |
59 | | - } |
60 | | - |
61 | | - public static class Solution3 { |
62 | | - //vertical scan |
63 | | - public String longestCommonPrefix(String[] strs) { |
64 | | - if (strs.length == 0) { |
65 | | - return ""; |
66 | | - } |
67 | | - for (int i = 0; i < strs[0].length(); i++) { |
68 | | - char c = strs[0].charAt(i); |
69 | | - for (int j = 1; j < strs.length; j++) { |
70 | | - if (i == strs[j].length() || strs[j].charAt(i) != c) { |
71 | | - return strs[0].substring(0, i); |
72 | | - } |
73 | | - } |
74 | | - } |
75 | | - return strs[0]; |
76 | | - } |
77 | | - } |
78 | 38 | } |
0 commit comments