最长公共前缀字符串

时间:2018-12-17 01:12:43

标签: recursion longest-prefix

Below is my recursive approach to finding the longest common prefix to a set of strings.

包递归;

public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] str) {
        String finalStr = longestCommonPrefixHelper(str,"");
        return finalStr;
    }
    public static String longestCommonPrefixHelper(String[] str,String prefix) {
        if(str.length==0) {
            return prefix;
        }
        System.out.println("Prefix is "+prefix);
        for(int i=0;i<str.length;i++) {
            if(str[i].equals("")) {
                return prefix;
            }
        }
        String ch = str[0].substring(0, 1);
        for(int i=0;i<str.length;i++) {
            if(!str[i].substring(0, 1).equals(ch)) {

                return prefix;
            }
            else if(str[i].length()>1)
                str[i] = str[i].substring(1, str[i].length());
            else
                str[i]="";
        }
        prefix= prefix+ch;
        longestCommonPrefixHelper(str, prefix);
        return prefix;
    }

    public static void display(String[] s) {
        for(int i=0;i<s.length;i++) {
            System.out.print(s[i]+" ");
        }
    }

    public static void main(String[] args) {
        String[] s = {"Sujit","Suhail","Suit","Susan"};

        System.out.println(longestCommonPrefix(s));
    }
}

由于某种原因,我没有得到正确的输出。碰巧有一件我错过的小事。非常感谢任何形式的帮助。预先感谢

1 个答案:

答案 0 :(得分:0)

更改此

prefix= prefix+ch;
longestCommonPrefixHelper(str, prefix);
return prefix;  

return longestCommonPrefixHelper(str, prefix+ch);

您忘了调用递归

  public class LongestCommonPrefix {
        public static String longestCommonPrefix(String[] str) {
            String finalStr = longestCommonPrefixHelper(str,"");
            return finalStr;
        }
        public static String longestCommonPrefixHelper(String[] str,String prefix) {
            if(str.length==0) {
                return prefix;
            }


            for(int i=0;i<str.length;i++) {
                if(str[i].equals("")) {
                    return prefix;
                }
            }

            String ch = str[0].substring(0, 1);
            for(int i=0;i<str.length;i++) {
                if(!str[i].substring(0, 1).equals(ch)) {
                    return prefix;
                }
                else if(str[i].length()>1)
                    str[i] = str[i].substring(1, str[i].length());
                else
                    str[i]="";
            }

            return longestCommonPrefixHelper(str, prefix+ch);
        }

        public static void display(String[] s) {
            for(int i=0;i<s.length;i++) {
                System.out.print(s[i]+" ");
            }
        }

        public static void main(String[] args) {
            String[] s = {"Sujit","Suhail","Suit","Susan"};

            System.out.println(longestCommonPrefix(s));
        }
    }