C# code, easy to understand


  • 0
    K

    The idea is expanding the sub-string in both directions from every point of the original string. Check if the sub-string is palindromic. The only thing we should notice is that a palindromic string can be formed in two ways: aba, abba. So we check them separately.

            public int CountSubstrings(string s)
            {
                if (s.Length == 0) return 0;
                int count = 1;
                for (int i = 1; i < s.Length; i++)
                {
                    // check the palindromic string in the format of aba. Of course, it will include the current char itself
                    int left = i, right = i;
                    while (left >= 0 && right <= s.Length - 1)
                    {
                        if (s[left] == s[right]) count++;
                        else break;
                        left--;
                        right++;
                    }
                    // check the palindromic string in the format of abba
                    left = i - 1; right = i;
                    while (left >= 0 && right <= s.Length - 1)
                    {
                        if (s[left] == s[right]) count++;
                        else break;
                        left--;
                        right++;
                    }
                }
                return count;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.