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 小时前
武器装备科研生产单位保密资质申请方法论:条件模型与流程拆解
人工智能·算法
是隼人8 小时前
buuctf-pwn xdctf2015_pwn200题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
en.en..8 小时前
C语言 标准输入 / 输出缓冲区
算法
吃好睡好便好10 小时前
查找函数的使用
学习·算法·matlab·生活·查找函数
学习星球10 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
靠沿11 小时前
贪心算法专题(二)
算法·贪心算法
布莱克60511 小时前
数组详解:定义、作用、应用场景及与链表的区别(C/C++ 代码讲解)
c语言·开发语言·c++·数组
hongmai66688811 小时前
MP2348GTL-Z:这颗24V/4A同步降压芯片,把性能和体积平衡得恰到好处
c语言·开发语言·arm开发·单片机·5g
多弗朗皮卡丘11 小时前
C语言梦开始的地方19:文件操作
c语言·开发语言
猎头南楼12 小时前
具身智能模型部署方向的能力要求与技术栈梳理
人工智能·深度学习·算法