Skip to content

Commit 6197be8

Browse files
authored
最长公共前缀题目,增加异常输入检查
1、检查元素是否含有null 2、检查是否String数组是否为0
1 parent e5925b5 commit 6197be8

File tree

1 file changed

+50
-31
lines changed

1 file changed

+50
-31
lines changed

数据结构与算法/搞定BAT面试——几道常见的子符串算法题.md

+50-31
Original file line numberDiff line numberDiff line change
@@ -108,38 +108,57 @@ public class Solution {
108108
思路很简单!先利用Arrays.sort(strs)为数组排序,再将数组第一个元素和最后一个元素的字符从前往后对比即可!
109109

110110
```java
111-
//https://leetcode-cn.com/problems/longest-common-prefix/description/
112111
public class Main {
113-
public static String replaceSpace(String[] strs) {
114-
115-
// 数组长度
116-
int len = strs.length;
117-
// 用于保存结果
118-
StringBuffer res = new StringBuffer();
119-
// 注意:=是赋值,==是判断
120-
if (strs == null || strs.length == 0) {
121-
return "";
122-
}
123-
// 给字符串数组的元素按照升序排序(包含数字的话,数字会排在前面)
124-
Arrays.sort(strs);
125-
int m = strs[0].length();
126-
int n = strs[len - 1].length();
127-
int num = Math.min(m, n);
128-
for (int i = 0; i < num; i++) {
129-
if (strs[0].charAt(i) == strs[len - 1].charAt(i)) {
130-
res.append(strs[0].charAt(i));
131-
} else
132-
break;
133-
134-
}
135-
return res.toString();
136-
137-
}
138-
//测试
139-
public static void main(String[] args) {
140-
String[] strs = { "customer", "car", "cat" };
141-
System.out.println(Main.replaceSpace(strs));//c
142-
}
112+
public static String replaceSpace(String[] strs) {
113+
114+
// 如果检查值不合法及就返回空串
115+
if (!chechStrs(strs)) {
116+
return "";
117+
}
118+
// 数组长度
119+
int len = strs.length;
120+
// 用于保存结果
121+
StringBuilder res = new StringBuilder();
122+
// 给字符串数组的元素按照升序排序(包含数字的话,数字会排在前面)
123+
Arrays.sort(strs);
124+
int m = strs[0].length();
125+
int n = strs[len - 1].length();
126+
int num = Math.min(m, n);
127+
for (int i = 0; i < num; i++) {
128+
if (strs[0].charAt(i) == strs[len - 1].charAt(i)) {
129+
res.append(strs[0].charAt(i));
130+
} else
131+
break;
132+
133+
}
134+
return res.toString();
135+
136+
}
137+
138+
private static boolean chechStrs(String[] strs) {
139+
boolean flag = false;
140+
// 注意:=是赋值,==是判断
141+
if (strs != null) {
142+
// 遍历strs检查元素值
143+
for (int i = 0; i < strs.length; i++) {
144+
if (strs[i] != null && strs[i].length() != 0) {
145+
flag = true;
146+
} else {
147+
flag = false;
148+
}
149+
}
150+
}
151+
return flag;
152+
}
153+
154+
// 测试
155+
public static void main(String[] args) {
156+
String[] strs = { "customer", "car", "cat" };
157+
// String[] strs = { "customer", "car", null };//空串
158+
// String[] strs = {};//空串
159+
// String[] strs = null;//空串
160+
System.out.println(Main.replaceSpace(strs));// c
161+
}
143162
}
144163

145164
```

0 commit comments

Comments
 (0)