zoukankan      html  css  js  c++  java
  • LeetCode 647. 回文子串 暴力模拟

    地址  https://leetcode-cn.com/problems/palindromic-substrings/

    给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
    
    具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
    
     
    
    示例 1:
    
    输入:"abc"
    输出:3
    解释:三个回文子串: "a", "b", "c"
    示例 2:
    
    输入:"aaa"
    输出:6
    解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
     
    
    提示:
    
    输入的字符串长度不会超过 1000

    算法1
    (暴力枚举) O(n)O(n)
    1 以每个字母为中心 每次左右向外扩展+1 查看字母是否相等。
    如果相等则是回文 如果不是则不必继续检测,因为已经出现不对称,不可能出现回文了
    2 以i i+1字母为中心 每次左右向外扩展+1 查看字母是否相等。
    如果相等则是回文 如果不是则不必继续检测,因为已经出现不对称,不可能出现回文了

    C++ 代码

    class Solution {
    public:
    
        bool Check(const string& s, int l, int r)
    {
        if (s[l] == s[r]) return true;
    
    
        return false;
    }
    
    int countSubstrings(string s) {
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            int l = i; int r = i;
            while (l >= 0 && r < s.size()) {
                if (Check(s, l, r)) ans++;
                else break;
                l--; r++;
            }
        }
    
        for (int i = 0; i < s.size(); i++) {
            int l = i; int r = i+1;
            while (l >= 0 && r < s.size()) {
                if (Check(s, l, r)) ans++;
                else break;
                l--; r++;
            }
        }
    
    
        return ans;
    }
    
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    129. Sum Root to Leaf Numbers
    113. Path Sum II
    114. Flatten Binary Tree to Linked List
    112. Path Sum
    100. Same Tree
    300. Longest Increasing Subsequence
    72. Edit Distance
    自定义js标签库
    JS 实现Table相同行的单元格自动合并示例代码
    mysql 高版本only_full_group_by 错误
  • 原文地址:https://www.cnblogs.com/itdef/p/13527466.html
Copyright © 2011-2022 走看看