forked from yuanguangxin/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
35 lines (33 loc) · 899 Bytes
/
Solution.java
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
package 字符串操作.q14_最长公共前缀;
/**
* 水平扫描 o(n)
*/
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String pre = "";
int i = 0;
while (true) {
if (strs[0].length() == i) {
return pre;
}
char temp = strs[0].charAt(i);
for (int k = 1; k < strs.length; k++) {
if (strs[k].length() == i || temp != strs[k].charAt(i)) {
return pre;
}
}
pre += temp;
i++;
}
}
public static void main(String[] args) {
String[] s = new String[]{"c", "c"};
System.out.println(new Solution().longestCommonPrefix(s));
}
}