-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
84 lines (79 loc) · 2.45 KB
/
Copy pathLongestCommonPrefix.java
File metadata and controls
84 lines (79 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* <p>编写一个函数来查找字符串数组中的最长公共前缀。</p>
*
* <p>如果不存在公共前缀,返回空字符串 <code>""</code>。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>strs = ["flower","flow","flight"]
* <strong>输出:</strong>"fl"
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>strs = ["dog","racecar","car"]
* <strong>输出:</strong>""
* <strong>解释:</strong>输入不存在公共前缀。</pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>1 <= strs.length <= 200</code></li>
* <li><code>0 <= strs[i].length <= 200</code></li>
* <li><code>strs[i]</code> 仅由小写英文字母组成</li>
* </ul>
* <div><div>Related Topics</div><div><li>字符串</li></div></div><br><div><li>👍 1987</li><li>👎 0</li></div>
*/
package leetcode9;
public class LongestCommonPrefix {
public static void main(String[] args) {
Solution solution = new LongestCommonPrefix().new Solution();
}
class Solution {
public String longestCommonPrefix(String[] strs) {
int max = Integer.MAX_VALUE;
for (String str : strs) {
max = Math.min(max, str.length() - 1);
}
int i = 0;
while (i <= max) {
char c = strs[0].charAt(i);
for (String str : strs) {
if (str.charAt(i) != c) {
return strs[0].substring(0, i);
}
}
i++;
}
return i > 0 ? strs[0].substring(0, i) : "";
}
}
class Solution2 {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
StringBuilder builder = new StringBuilder();
int max = strs[0].length() - 1;
for (int i = 0; i <= max; i++) {
char c = strs[0].charAt(i);
for (String str : strs) {
if (i >= str.length()) {
return builder.toString();
}
if (str.charAt(i) != c) {
return builder.toString();
}
}
builder.append(c);
}
return builder.toString();
}
}
}