题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
import java.util.*;
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
// 可以使用一个数组存储每个字母出现的次数,找到出现次数最多的
// 找到最短的字符串,然后遍历
if (strs == null || strs.length == 0) {
return "";
}
String res = strs[0];
// 先找到最短的字符串
for (int i = 0; i < strs.length; ++i) {
if (strs[i].length() < res.length()) {
res = strs[i];
}
}
System.out.println(res);
// boolean flag = true;
while (res.length() != 0) {
boolean flag = true;
for (int i = 0; i < strs.length; ++i) {
if (!(strs[i].substring(0, res.length()).equals(res))) {
flag = false;
}
}
if (flag) {
break;
} else {
res = res.substring(0, res.length() - 1);
}
}
return res;
}
}

曼迪匹艾公司福利 115人发布