Skip to content

Latest commit

 

History

History

1156

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a string text, we are allowed to swap two of the characters in the string. Find 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", which its length is 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", which its length is 6.

Example 3:

Input: text = "aaabbaaa"
Output: 4

Example 4:

Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.

Example 5:

Input: text = "abcdef"
Output: 1

 

Constraints:

  • 1 <= text.length <= 20000
  • text consist of lowercase English characters only.

Companies:
Amazon

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
    int cnt[26] = {};
    int maxRep(string &s, char c) {
        int ans = 0, prev = -1, mid = -1;
        for (int i = 0; i <= s.size(); ++i) {
            if (i < s.size() && s[i] == c) continue;
            int len = i - prev - 1;
            if (mid != -1 && len - 1 == cnt[c - 'a']) --len;
            ans = max(ans, len);
            prev = mid;
            mid = i;
        }
        return ans;
    }
public:
    int maxRepOpt1(string s) {
        int ans = 0;
        for (char c : s) cnt[c - 'a']++;
        for (char c = 'a'; c <= 'z'; ++c) {
            ans = max(ans, maxRep(s, c));
        }
        return ans;
    }
};