The Problem Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Examples Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Constraints 1 <= s.length <= 1000 s consists of lowercase English letters. Brute Force Solution func countSubstrings(_ s: String) -> Int { let n = s.count let sArray = Array(s) var res = 0 for i in 0 ..< n { for j in i ..< n { var l = i var r = j while l < r && sArray[l] == sArray[r] { l += 1 r -= 1 } res += (l >= r) ? 1 : 0 } } return res } Explanation We can solve this problem by understanding how a brute-force approach works and then optimizing it.
...