zoukankan      html  css  js  c++  java
  • LeetCode 437 回文子串

    LeetCode 437 回文子串

    题目描述:给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
    具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

    执行用时:3 ms, 在所有 Java 提交中击败了91.69%的用户
    内存消耗:37.6 MB, 在所有 Java 提交中击败了91.75%的用户

    中心扩散

    class Solution {
        public int countSubstrings(String s) {
            /*边界条件*/
            if(s==null || s.length()==0) {
                return 0;
            }
            /*遍历每一个字符,使用中心扩散法计数*/
            int result = 0;
            for(int i=0; i<s.length(); i++) {
                result += count(i, s);
            }
    
            return result;
        }
    
        /*中心扩散计数*/
        public int count(int startIdx, String s) {
            int result = 1; //元素本身算一个回文子串
            int leftBound, riughtBound;
            //偶数情况(无中心,只向右看,避免重复)
            if(startIdx<s.length()-1 && s.charAt(startIdx)==s.charAt(startIdx+1)) {
                leftBound = startIdx-1;
                riughtBound = startIdx+2;
                result++;   //最中心处的对称
                result += centralDiffusion(leftBound, riughtBound, s);
            }
            //奇数(中心向两边看)
            if((startIdx>0 && startIdx<s.length()-1)) {
                leftBound = startIdx-1;
                riughtBound = startIdx+1;
                result += centralDiffusion(leftBound, riughtBound, s);
            }
    
            return result;
        }
    
        /*中心扩散*/
        public int centralDiffusion(int leftBound, int riughtBound, String s) {
            int result = 0;
            while(leftBound>=0 && riughtBound<=(s.length()-1)) {
                if(s.charAt(leftBound)!=s.charAt(riughtBound)) {
                    break;
                }
                leftBound--;
                riughtBound++;
                result++;
            }
            return result;
        }
    }
    
  • 相关阅读:
    2013.11.3
    计算机面试书籍
    SDPLR的安装过程(matlab)
    Semi-definite programming优化工具
    R-note1
    Ubuntu---2
    C#中DataTable转换为string
    MFC获取字符串长度的5中方法
    根据不同的操作系统(64/32),设置文件以64位运行。又可解决问题:“试图加载不正确的程序”。
    WinServer2008下通过powershell获取IIS等角色功能列表,保存至txt
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13527324.html
Copyright © 2011-2022 走看看