Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3335f63

Browse files
committed
纵向比较
1 parent 5c4c920 commit 3335f63

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed

app/src/main/java/com/zhxh/codeproj/leetcode/top145/LeetCode14.java

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,36 @@
11
package com.zhxh.codeproj.leetcode.top145;
22

33
/*
4+
14. 最长公共前缀
45
编写一个函数来查找字符串数组中的最长公共前缀。
56
6-
公共前缀 前缀
7+
如果不存在公共前缀,返回空字符串 ""。
78
8-
如果不存在公共前缀,返回空字符串""。
99
10-
示例1:
1110
12-
输入: ["flower","flow","flight"]
13-
输出: "fl"
14-
示例2:
11+
示例 1:
1512
16-
输入: ["dog","racecar","car"]
17-
输出: ""
18-
解释: 输入不存在公共前缀。
19-
说明:
13+
输入:strs = ["flower","flow","flight"]
14+
输出:"fl"
15+
示例 2:
2016
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] 仅由小写英文字母组成
2227
2328
*/
2429

2530
public class LeetCode14 {
2631
public static void main(String[] args) {
2732
System.out.print(new Solution().longestCommonPrefix(new String[]{"flowsad", "flosad", "flisad"}));
33+
System.out.print(new Solution2().longestCommonPrefix(new String[]{"flowsad", "flosad", "flisad"}));
2834
}
2935

3036
/*
@@ -50,4 +56,26 @@ public String longestCommonPrefix(String[] strs) {
5056
return res.toString();
5157
}
5258
}
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+
}
5381
}

0 commit comments

Comments
 (0)