File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -278,5 +278,41 @@ public class StringUtil {
278
278
return s. substring(ll, rr + 1 );
279
279
}
280
280
281
+
282
+ /**
283
+ * 8、字符串最长公共前缀问题
284
+ *
285
+ **/
286
+ public static String longestCommonPrefix (String [] strs ) {
287
+ if (strs == null || strs. length == 0 ) {
288
+ return " " ;
289
+ }
290
+ // 拿出第一个字符串。当成初始值
291
+ char [] chs = strs[0 ]. toCharArray();
292
+ // 所有字符串都匹配的最大长度,等同于每个字符串和初始字符串匹配的全局最小长度
293
+ int min = Integer . MAX_VALUE ;
294
+
295
+ for (String str : strs) {
296
+
297
+ char [] tmp = str. toCharArray();
298
+ int index = 0 ;
299
+ while (index < tmp. length && index < chs. length) {
300
+ if (chs[index] != tmp[index]) {
301
+ break ;
302
+ }
303
+ index++ ;
304
+ }
305
+ // 更新min
306
+ min = Math . min(index, min);
307
+ // 如果有任意一个字符串和初始串不匹配,直接返回""
308
+ if (min == 0 ) {
309
+ return " " ;
310
+ }
311
+ }
312
+ // 截取min的长度,就是所有字符串共同匹配的最大长度
313
+ return strs[0 ]. substring(0 , min);
314
+ }
315
+
316
+
281
317
}
282
318
```
You can’t perform that action at this time.
0 commit comments