程式語言 - LeetCode - C++ - 647. Palindromic Substrings



題目:


解答:

class Solution {
public:
    int countSubstrings(string s) {
        int n = s.size();

        auto chk = [&](int l, int r) -> int {
            int cnt = 0;

            while (l >= 0 && r < n && s[l] == s[r]) {
                l -= 1;
                r += 1;
                cnt += 1;
            }

            return cnt;
        };

        int ans = 0;

        for (int i = 0; i < n; ++i) {
            ans += chk(i, i);
            ans += chk(i, i + 1);
        }

        return ans;
    }
};