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; } }