【算法】【字符串】Leetcode迴文子串相關題目

最長迴文子串

題目鏈接: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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章