DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #647. Palindromic Substrings

Brute force solution

Time Complexity: 0(n^3)

Space Complexity: O(1)

class Solution {
    public int countSubstrings(String s) {
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++){
                if (isPalindrome(s, i, j)) {
                    count++;
                }
            }
        }
        return count;

    }

    public boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) return false;

            start++;
            end--;
        }
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)