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;
        }
    }
    
  • 相关阅读:
    数据库表之间的联合查询
    c# 后台调前台的js
    oracle创建视图
    设置Crystal Report的FieldObject换行
    在XAML中转义大括号
    运行水晶报表报crdb_adoplus.dll不存在错误的解决方案
    网页面里动态添加linkbutton或者button
    正则表达式
    实现checkbox全选。html dom对象和jquery dom对象。
    手把手教你做关键词匹配项目(搜索引擎) 第二天
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13527324.html
Copyright © 2011-2022 走看看