Palindromic Substrings

Palindromic Substrings

    public int countSubstrings(String s) {
        int count = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            for (int j = i; j < length; j++) {
                if (isPalindromic(i, j, s)) {
                    count++;
                }

            }
        }
        return count;
    }

    public boolean isPalindromic(int start, int end, String s) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
    int count = 0;

    public int countSubstrings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        for (int i = 0; i < s.length(); i++) {
            extend(s, i, i);
            extend(s, i, i + 1);
        }

        return count;
    }

    public void extend(String str, int left, int right) {
        while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
            count++;
            left--;
            right++;
        }
        return;
    }

你可能感兴趣的:(Palindromic Substrings)