最长公共前缀
题目说明: * 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
示例 1: * 输入:strs = ["flower","flow","flight"] * 输出:"fl" * 示例 2: * 输入:strs = ["dog","racecar","car"] * 输出:"" * 解释:输入不存在公共前缀。 *
public class LongestCommonPrefix_0004 {public static void main(String[] args) {// 测试验证代码}public static String longestCommonPrefix(String[] strs) {return null;}
}
结果:
public class LongestCommonPrefix_0004 {public static void main(String[] args) {String[] strs = new String[]{"flower", "flow", "flight"};System.out.println(LongestCommonPrefix_0004.longestCommonPrefix(strs));}public static String longestCommonPrefix(String[] strs) {//首先判断它的字符串是否为空,如果为空则返回为空字符。if (strs.length == 0) {return "";}//定义一个临时变量String temp = strs[0];for (int i = 1; i < strs.length; i++) {int j = 0;for (; j < temp.length() && j < strs[i].length(); j++) {//如果temp的单字符 不同与 strs则直接结束if (temp.charAt(j) != strs[i].charAt(j)) {break;}}//获取到共同前缀temp = temp.substring(0, j);// 判断共同前缀是否为空if (temp.equals("")) {return temp;}}return temp;}
}