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;
}
相关推荐
wabs6668 分钟前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin0311 分钟前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
shehuiyuelaiyuehao44 分钟前
算法50,分治归并,数组中的逆序对
java·算法
阳明山水1 小时前
校准分位数驱动智能库存决策
人工智能·深度学习·算法·机器学习·架构
91刘仁德2 小时前
C++ 继承和多态 设计模式
c语言·c++·笔记
码行山野赴时序归途2 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
库玛西2 小时前
哈夫曼树与前缀编码:数据压缩的贪心核心
c语言·c++·笔记·考研
别动我齐刘海3 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
zhangfeng11333 小时前
《从“人工适配“到“智能生成“:KernelSwift 跨国产芯片算子迁移全栈方案解读》 —— 强调范式跃迁和跨硬件属性,适合偏架构分析的写法
人工智能·算法·华为·ai编程·npu
0+1113 小时前
算法 --滑动窗口
c++·算法·leetcode