[LeetCode Java] 14 Longest Common Prefix

来源:互联网 发布:土行孙智能网络加速 编辑:程序博客网 时间:2024/06/05 09:56
/** *  * Write a function to find the longest common prefix string amongst an array of strings. * */public class LongestCommonPrefix {static String longestCommonPrefix(String[] strs) {if (strs.length == 0) return "";String compareStr = strs[0];int commonIndex = strs[0].length() - 1;for (int i = 1; i < strs.length; i++) {if(strs[i].length() == 0) return "";for (int j = 0; j < strs[i].length() && j <= commonIndex; j++) {if (compareStr.charAt(j) != strs[i].charAt(j)) {commonIndex = j - 1;break;}if (j == strs[i].length() - 1) commonIndex = j;}}return compareStr.substring(0, commonIndex + 1);}public static void main(String[] args) {String[] strs = {"abcd", "abcd", "abcd", "abcdc"};System.out.println(longestCommonPrefix(strs));String[] strs1 = {""};System.out.println(longestCommonPrefix(strs1));}}

0 0