1
1
package com .zhxh .codeproj .leetcode .top145 ;
2
2
3
3
/*
4
+ 14. 最长公共前缀
4
5
编写一个函数来查找字符串数组中的最长公共前缀。
5
6
6
- 公共前缀 前缀
7
+ 如果不存在公共前缀,返回空字符串 ""。
7
8
8
- 如果不存在公共前缀,返回空字符串""。
9
9
10
- 示例1:
11
10
12
- 输入: ["flower","flow","flight"]
13
- 输出: "fl"
14
- 示例2:
11
+ 示例 1:
15
12
16
- 输入: ["dog","racecar","car"]
17
- 输出: ""
18
- 解释: 输入不存在公共前缀。
19
- 说明:
13
+ 输入:strs = ["flower","flow","flight"]
14
+ 输出:"fl"
15
+ 示例 2:
20
16
21
- 所有输入只包含小写字母a-z。
17
+ 输入:strs = ["dog","racecar","car"]
18
+ 输出:""
19
+ 解释:输入不存在公共前缀。
20
+
21
+
22
+ 提示:
23
+
24
+ 1 <= strs.length <= 200
25
+ 0 <= strs[i].length <= 200
26
+ strs[i] 仅由小写英文字母组成
22
27
23
28
*/
24
29
25
30
public class LeetCode14 {
26
31
public static void main (String [] args ) {
27
32
System .out .print (new Solution ().longestCommonPrefix (new String []{"flowsad" , "flosad" , "flisad" }));
33
+ System .out .print (new Solution2 ().longestCommonPrefix (new String []{"flowsad" , "flosad" , "flisad" }));
28
34
}
29
35
30
36
/*
@@ -50,4 +56,26 @@ public String longestCommonPrefix(String[] strs) {
50
56
return res .toString ();
51
57
}
52
58
}
59
+
60
+ /*
61
+ 纵向比较
62
+ */
63
+ static class Solution2 {
64
+ public String longestCommonPrefix (String [] strs ) {
65
+ if (strs == null || strs .length == 0 ) {
66
+ return "" ;
67
+ }
68
+ int length = strs [0 ].length ();
69
+ int count = strs .length ;
70
+ for (int i = 0 ; i < length ; i ++) {
71
+ char c = strs [0 ].charAt (i );
72
+ for (int j = 1 ; j < count ; j ++) {
73
+ if (i == strs [j ].length () || strs [j ].charAt (i ) != c ) {
74
+ return strs [0 ].substring (0 , i );
75
+ }
76
+ }
77
+ }
78
+ return strs [0 ];
79
+ }
80
+ }
53
81
}
0 commit comments