zoukankan      html  css  js  c++  java
  • 647. Palindromic Substrings

    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.

    Example 1:

    Input: s = "abc"
    Output: 3
    Explanation: Three palindromic strings: "a", "b", "c".
    

    Example 2:

    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.
    class Solution {
        public int countSubstrings(String s) {
            int n = s.length();
            int res = n;
            for(int i = 2; i <= n; i++) {
                for(int j = 0; j <= n - i; j++) {
                    if(help(s.substring(j, j + i))) {
                        res++;
                    }
                }
            }
            return res;
        }
        public boolean help(String s) {
            int l = 0, r = s.length() - 1;
            while(l < r) {
                if(s.charAt(l) != s.charAt(r)) return false;
                l++;
                r--;
            }
            return true;
        }
    }

    mlgb, brute force管上。

    class Solution {
        int res = 0;
        public int countSubstrings(String s) {
            int n = s.length();
            for(int i = 0; i < s.length(); i++) {
                help(s, i, i);
                help(s, i, i + 1);
            }
            return res;
        }
        
        public void help(String s, int l, int r) {
            while(l >= 0 && r <= s.length() - 1 && s.charAt(l) == s.charAt(r)) {
                res++;
                l--;
                r++;
            }
        }
    }

    或者用一种和5一样的midexpansion方法,每次check这一位开始的odd和even的substring看是不是palindrome。

  • 相关阅读:
    dayfunctools.weps 定义函数装饰器
    python3之concurrent.futures一个多线程多进程的直接对接模块,python3.2有线程池了
    python的类的super()
    django的admin
    python的单例模式
    git指南
    django创建验证码
    Django model对象接口
    Go语言基础
    迭代器&迭代对象&生成器
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/15033646.html
Copyright © 2011-2022 走看看