zoukankan      html  css  js  c++  java
  • 【算法】【字符串】Leetcode回文子串相关题目

    中心扩散法

    int expand(string s, int i, int j)
        {
            int n = s.size();
            int cnt = 0;
            while(i >= 0 && j < n)
            {
                if(s[i] == s[j])
                {
                     cnt++;
                     i--;
                     j++;
                }
                else break;
            }
            return cnt;    
        }
    

    最长回文子串

    题目链接:https://leetcode-cn.com/problems/longest-palindromic-substring/

    class Solution {
    public:
        pair<int, int> expand(string s, int i, int j)
        {
            while(i >= 0 && j < s.size() && s[i] == s[j])
            {
                --i;
                ++j;
            }
            return {i + 1, j - 1};
        }
        string longestPalindrome(string s) {
            int cnt = 0;
            pair<int, int> pii;
            for(int i = 0; i < s.size(); i++)
            {
                auto val_1 = expand(s, i, i);
                
                auto val_2 = expand(s, i, i + 1);
    
                int cnt_1 = val_1.second - val_1.first + 1;
                if(cnt_1 > cnt)
                {
                    cnt = cnt_1;
                    pii = val_1;
                }
    
    
                int cnt_2 = val_2.second - val_2.first + 1;
                if(cnt_2 > cnt)
                {
                    cnt = cnt_2;
                    pii = val_2;
                }
                
            }
            return s.substr(pii.first, pii.second - pii.first + 1);
        }
    };
    

    回文子串

    题目链接:https://leetcode-cn.com/problems/palindromic-substrings/

    class Solution {
    public:
        int expand(string s, int i, int j)
        {
            int n = s.size();
            int cnt = 0;
            while(i >= 0 && j < n)
            {
                if(s[i] == s[j])
                {
                     cnt++;
                     i--;
                     j++;
                }
                else break;
            }
            return cnt;
    
            
        }
        int countSubstrings(string s) {
            int cnt = 0;
            for(int i = 0; i < s.size(); i++)
            {
                cnt += expand(s, i, i);
                cnt += expand(s, i, i + 1);
            }
            return cnt;
        }
    };
    
  • 相关阅读:
    js中replace的正则替换
    ios沙盒路径
    Android开源框架
    小知识点
    __NSCFConstantString && __NSPlaceholderDictionary
    iq 格式分析
    C 函数
    Xcode报错
    XMPP Server
    H5网站借鉴
  • 原文地址:https://www.cnblogs.com/Trevo/p/13517695.html
Copyright © 2011-2022 走看看