647.回文子串

647.回文子串

image-20200819232720148

题解

​ 计算回文串的个数,使用回文中心法时间复杂度会更优,即以当前字符为中心,向左右两边遍历,若不同则移动字符中心。可以发现每个长度为n的字符串,能且只能生成2n-1组回文组合,从0遍历到2n-2即可统一n为奇数和偶数的情况。

class Solution {
    
    
    public int countSubstrings(String s) {
    
    
        int n = s.length(), ans = 0;
        for (int i = 0; i < 2 * n - 1; ++i) {
    
    
            int l = i / 2, r = i / 2 + i % 2;
            while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) {
    
    
                --l;
                ++r;
                ++ans;
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Rush6666/article/details/108113580