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;
}
相关推荐
Reart18 小时前
Leetcode 1143.最长公共子序列(720)
后端·算法
无相求码18 小时前
const vs #define:C语言常量定义的差异
c语言·算法
Android洋芋18 小时前
AI辅助C盘清理
c语言·开发语言·人工智能·ai辅助c盘清理
ScilogyHunter18 小时前
GCC/Clang 原始字符串详解
c语言·原始字符串
先吃饱再说18 小时前
LeetCode 226. 翻转二叉树
算法
剑锋所指,所向披靡!19 小时前
数据结构之关键路径
数据结构·算法
阿宇的技术日志19 小时前
漏桶、令牌桶、滑动窗口 三限流算法理解
算法·滑动窗口·漏桶·令牌桶
来一碗刘肉面19 小时前
队列的链式实现
数据结构·c++·算法·链表
KaMeidebaby19 小时前
卡梅德生物技术快报|原核膜蛋白表达优化实操手册,膜蛋白的纯化梯度洗脱完整流程
前端·网络·数据库·人工智能·算法