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;
        }
    }
    
  • 相关阅读:
    memory runs at single channel问题解决
    ASP php获取文件URL地址等方法
    zencart的modules下数据库操作templates排版和common首页引用
    php生成html 伪静态??
    Linux服务器自动备份压缩MySQL数据库的实用方法
    dos 命令集
    Zencart 500错误查找和解决方法
    破解JS加密:url unicode加密而已
    .htaccess 保护文件夹
    TCP 的那些事儿(上)
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13527324.html
Copyright © 2011-2022 走看看