Repository navigation
Expand file tree
/
Copy pathlc14.java
More file actions
49 lines (43 loc) · 1.37 KB
/
Copy pathlc14.java
File metadata and controls
49 lines (43 loc) · 1.37 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
public class lc14 {
//class Solution {
// public String longestCommonPrefix(String[] strs) {
// if (strs == null || strs.length == 0)
// return "";
/// for (int i = 0; i < strs[0].length(); i++) {
// char c = strs[0].charAt(i);
/// for (int j = 1; j < strs.length; j++) {
// return strs[0].substring(0, i);}}}
// return strs[0];
//
// }
// }
//class Solution {
// public String longestCommonPrefix(String[] strs) {
// String prefix = "";
// for (int i = 0; i < strs[0].length(); i++) {
// char ch = strs[0].charAt(i);
// for (String str : strs) {
// if (i >= str.length() || str.charAt(i) != ch) {
// return prefix;
// }
// }
// prefix += ch;
// }
// return prefix; }
//}
class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder prefix = new StringBuilder();
for (int i = 0; i < strs[0].length(); i++) {
char ch = strs[0].charAt(i);
for (String str : strs) {
if (i >= str.length() || str.charAt(i) != ch) {
return prefix.toString();
}
}
prefix.append(ch);
}
return prefix.toString();
}
}
}