1. 程式人生 > 其它 >LeetCode 1156. 單字元重複子串的最大長度

LeetCode 1156. 單字元重複子串的最大長度

技術標籤:LeetCode

文章目錄

1. 題目

如果字串中的所有字元都相同,那麼這個字串是單字元重複的字串。

給你一個字串 text,你只能交換其中兩個字元一次或者什麼都不做,然後得到一些單字元重複的子串。
返回其中最長的子串的長度。

示例 1:
輸入:text = "ababa"
輸出:3

示例 2:
輸入:text = "aaabaaa"
輸出:6

示例 3:
輸入:text = "aaabbaaa"
輸出:4

示例 4:
輸入:text = "aaaaa"
輸出:5
示例 5: 輸入:text = "abcdef" 輸出:1 提示: 1 <= text.length <= 20000 text 僅由小寫英文字母組成。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/swap-for-longest-repeated-character-substring
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

2. 解題

  • 把每個字元,每段的開始結束位置存起來
  • 在檢查相鄰的段之間的間距是不是1,進行分類討論
class Solution {
public:
    int
maxRepOpt1(string text) { text.push_back('-');//方便程式碼處理 vector<vector<vector<int>>> p(26); // 存放每個字元每個連續段的 {開始位置,結束位置} char prev = text[0]; int start = 0, ans = 1; for(int i = 0; i < text.size(); ++i) { if(text[i] != prev)
{ p[prev-'a'].push_back({start, i-1}); ans = max(ans, i-start);//什麼都不做的情況下的最大長度 start = i; prev = text[i]; } } for(int i = 0; i < 26; ++i) { int len = p[i].size();//有多少段該字元 for(int j = 1; j < len; ++j) { int prevEnd = p[i][j-1][1]; int n1 = p[i][j-1][1]-p[i][j-1][0]+1; int curStart = p[i][j][0]; int n2 = p[i][j][1]-p[i][j][0]+1; if(curStart-prevEnd == 2)//隔一個字元 { ans = max(ans, n1+n2+(len>2 ? 1 : 0)); } //3段及以上,可以在多新增1個字元進來 else//間隔多個字元 { ans = max(ans, max(n1+1, n2+1)); } // 兩段不能聯通,只能過去1個字元 } } return ans; } };

20 ms 11.7 MB C++


我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明