javastringalgorithmcomplexity-theory

Calculating longest Palindrome substring in the String


I have the following code for calculating the longest palindrome sub string in the string. The online judge accepts O(n^2) solution but i don't know why it is not accepting my solution although it seems that my algorithm is O(n^2) in complexity.`

class Ideone {

    public static void main(String args[]) {
        Ideone ob = new Ideone();
        String s = "sds";
        System.out.println(ob.longestPalindrome(s));

    }

    public String longestPalindrome(String s) {
        int maxlength = 1;

        String ps = s.charAt(0) + "";

        if (s.length() == 1)
            return s;
        for (int i = 0; i < s.length() - 1; i++) {
            int j = (s.substring(i + 1)).indexOf(s.charAt(i)) + i + 1;
            while (j < s.length() && j > i) {
                if (j - i + 1 > maxlength && check(s.substring(i, j + 1))) {

                    maxlength = j - i + 1;
                    ps = s.substring(i, j + 1);

                }
                if ((s.substring(j + 1)).indexOf(s.charAt(i)) < 0) {
                    break;
                }
                j = (s.substring(j + 1)).indexOf(s.charAt(i)) + j + 1;

            }
        }


        return ps;
    }

    public boolean check(String s) {
        int l = s.length();
        if (l == 1)
            return false;
        int t = l / 2;
        String s1, s2;
        if (l % 2 == 0) {
            s1 = s.substring(0, t);
            s2 = s.substring(t);

        } else {
            s1 = s.substring(0, t);
            s2 = s.substring(t + 1);

        }

        s2 = (new StringBuffer(s2)).reverse().toString();

        if (s1.compareTo(s2) == 0)
            return true;
        else return false;
    }

}

Solution

  • At first glimpse two loops and a method check() which needs O(n) to reverse the String might lead to O(n³).

    Be aware that methods like:

    Need to iterate through the data and therefore need about O(n) and not constant time.