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;
}
相关推荐
十月的皮皮9 分钟前
STM32从零到量产开发:四路继电器工业控制模块开发 -上位机 Program.cs 应用程序入口设计说明
c语言·stm32·单片机·stm32cubemx·hal库
坚持编程的菜鸟22 分钟前
模拟实现memcpy
c语言·算法·模拟实现my_memcpy
wabs66627 分钟前
关于图论【最短路径之Bellman_ford 算法|卡码网94.城市间货物运输的思考】
数据结构·算法·图论·卡码网·bellman_ford·求最短路径
MrZhao40029 分钟前
On-Policy Distillation(OPD):为什么大模型后训练要在学生自己的轨迹上蒸馏?
算法
小小龙学IT38 分钟前
Day 28 项目调试与优化 —— 给聊天室做一次“全面体检“
c语言·开发语言
朱峥嵘(朱髯)40 分钟前
数据库如何根据全表 NDV 估算子集的 NDV
数据库·算法
jjjava2.01 小时前
牛客算法题(第四期)
算法
雪碧聊技术1 小时前
力扣 回溯法 | LCR 020. 回文子串
javascript·算法·leetcode
wabs6661 小时前
关于哈希表【力扣454.四数相加II的思考】
数据结构·算法·leetcode·散列表
我能坚持多久1 小时前
优选算法——专题一双指针(上):附四道例题详解
c++·学习·算法