最长的公共前缀


题目:最长的公共前缀

/**
 * 类型 --->  最长的公共前缀
 *
 * 我的思路:  木桶效应,找到最短的那个元素,然后进行对比
 */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        Solution2 solution = new Solution2();
        String[] strings = {"flower","flow","flight"};
        solution.longestCommonPrefix(strings);
    }
}



上面是测试
//------------------------
下面是分装好的代码



/**
 * 示例 1:
 * 输入:strs = ["flower","flow","flight"]
 * 输出:"fl"
 * 示例 2:
 * 

*

* 输入:strs = ["dog","racecar","car"] * 输出:"" * 解释:输入不存在公共前缀。 */ class Solution2 { public void longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) throw new RuntimeException("你的输入有误"); /** * 这个可以快速得出, ["flower","flow","flight"] 这样的String[]的数组,n个元素中的,最短的元素长度。 * 那上面这个做解释:因为最短的是"flow"所以, minLengthRow出来的结果是 = 4; */ int minLengthRow = 201; for (String str : strs) { minLengthRow = Math.min(minLengthRow, str.length()); } //得出String[]中元素个数(列的个数) int column = strs.length; String shortString = null; //得到最短的那个元素,也就是最长的相同开头 for (int i = 0; i < strs.length; i++) { if (strs[i].length() == minLengthRow) { shortString = strs[i]; } } //把最短的那个元素,和其他的进行对比,得出开头 for (int i = 0; i < minLengthRow; i++) { char shortEveyChar = shortString.charAt(i); for (int j = 0; j < column; j++) { if(shortString.charAt(0) != strs[j].charAt(0)){ System.out.println("没有相同前缀");; return; } if (strs[j].charAt(i) != shortEveyChar) { System.out.println(shortString.substring(0, i)); return; } } } System.out.println( shortString); return; } }

图片解析: