LeetCode //C - 1156. Swap For Longest Repeated Character Substring

1156. Swap For Longest Repeated Character Substring

You are given a string text. You can swap two of the characters in the text.

Return the length of the longest substring with repeated characters.

Example 1:

Input: text = "ababa"

Output: 3

Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.

Example 2:

Input: text = "aaabaaa"

Output: 6

Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.

Example 3:

Input: text = "aaaaa"

Output: 5

Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.

Constraints:
  • 1 < = t e x t . l e n g t h < = 2 ∗ 10 4 1 <= text.length <= 2 * 10^4 1<=text.length<=2∗104
  • text consist of lowercase English characters only.

From: LeetCode

Link: 1156. Swap For Longest Repeated Character Substring


Solution:

Ideas:

count total letters, scan same-character blocks, then either extend one block by 1 or merge two blocks separated by one different character.

Code:
c 复制代码
int maxRepOpt1(char* text) {
    int total[26] = {0};
    int n = 0;

    while (text[n]) {
        total[text[n] - 'a']++;
        n++;
    }

    int ans = 0;

    for (int i = 0; i < n; ) {
        int j = i;
        while (j < n && text[j] == text[i]) {
            j++;
        }

        int ch = text[i] - 'a';
        int len1 = j - i;

        // Case 1: extend this block by swapping one same char from elsewhere
        if (total[ch] > len1)
            ans = ans > len1 + 1 ? ans : len1 + 1;
        else
            ans = ans > len1 ? ans : len1;

        // Case 2: combine two same-char blocks separated by one different char
        int k = j + 1;
        if (j < n && k < n && text[k] == text[i]) {
            while (k < n && text[k] == text[i]) {
                k++;
            }

            int len2 = k - (j + 1);
            int combined = len1 + len2;

            if (total[ch] > combined)
                combined++;

            if (combined > ans)
                ans = combined;
        }

        i = j;
    }

    return ans;
}
相关推荐
沐晓时光7 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
信奥卷王7 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵7 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
SuperByteMaster8 小时前
wfi进入之前没有清除basepri, 导致中断优先级不够,wfi 退不出来
c语言
徐小黑ACG8 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z9 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛9 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记9 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序10 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm