Skip to content

Commit 9951930

Browse files
author
dai
committed
字符串最长公共前缀问题
1 parent f6c16cd commit 9951930

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

27-算法面试专题-字符串.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,5 +278,41 @@ public class StringUtil {
278278
return s.substring(ll, rr + 1);
279279
}
280280

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+
281317
}
282318
```

0 commit comments

Comments
 (0)