class Solution { // 定义一个方法,用于查找字符串数组中所有字符串的最长公共前缀 public String longestCommonPrefix(String[] strs) { // 如果输入的字符串数组为空或者长度为0,直接返回空字符串 if (strs == null || strs.length == 0){ return ""; } // 使用StringBuilder来构建最长公共前缀 StringBuilder sb = new StringBuilder(); // 遍历第一个字符串的每一个字符 for (int i = 0;i < strs[0].length();i++){ // 获取当前位置的字符 char c = strs[0].charAt(i); // 遍历其他字符串,检查当前位置的字符是否相同 for (int j = 1;j < strs.length;j++){ // 如果当前位置超出了某个字符串的长度,或者当前位置的字符与其他字符串不同,则返回已构建的前缀 if (i >= strs[j].length() || strs[j].charAt(i) != c){ return sb.toString(); } } // 如果当前位置的字符在所有字符串中都相同,将其添加到前缀中 sb.append(c); } // 返回构建好的最长公共前缀 return sb.toString(); } }
07-27