Skip to content

Commit 057fe04

Browse files
author
changhongyuan
committed
第14题
1 parent ef2c0c9 commit 057fe04

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

.idea/leetcode/editor.xml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//编写一个函数来查找字符串数组中的最长公共前缀。
2+
//
3+
// 如果不存在公共前缀,返回空字符串 ""。
4+
//
5+
// 示例 1:
6+
//
7+
// 输入: ["flower","flow","flight"]
8+
//输出: "fl"
9+
//
10+
//
11+
// 示例 2:
12+
//
13+
// 输入: ["dog","racecar","car"]
14+
//输出: ""
15+
//解释: 输入不存在公共前缀。
16+
//
17+
//
18+
// 说明:
19+
//
20+
// 所有输入只包含小写字母 a-z 。
21+
// Related Topics 字符串
22+
// 👍 1386 👎 0
23+
24+
package com.changhongyuan.leetcode.editor.cn;
25+
class LongestCommonPrefix{
26+
//leetcode submit region begin(Prohibit modification and deletion)
27+
class Solution {
28+
public String longestCommonPrefix(String[] strs) {
29+
String result = "";
30+
if (null == strs || strs.length == 0 || null == strs[0]) {
31+
return result;
32+
}
33+
int minLength = strs[0].length();
34+
for (String s : strs) {
35+
minLength = Math.min(minLength, s.length());
36+
}
37+
for (int i = 0; i < minLength; i++) {
38+
boolean isEqual = true;
39+
for (int j = 0; j < strs.length - 1; j++) {
40+
if (strs[j].charAt(i) != strs[j + 1].charAt(i)) {
41+
isEqual = false;
42+
break;
43+
}
44+
}
45+
if (isEqual) {
46+
result += strs[0].charAt(i);
47+
} else {
48+
break;
49+
}
50+
}
51+
return result;
52+
}
53+
}
54+
//leetcode submit region end(Prohibit modification and deletion)
55+
56+
public static void main(String[] args) {
57+
Solution solution = new LongestCommonPrefix().new Solution();
58+
String[] strs = new String[10];
59+
System.out.println(solution.longestCommonPrefix(strs));
60+
}
61+
}

0 commit comments

Comments
 (0)