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.
Solution: HashTable
Pre-processing
- Compute the longest repeated substring starts and ends with text[i].
- Count the frequency of each letter.
Main
- Loop through each letter
- Check the left and right letter
- if they are the same, len = left + right
- e.g1. “aa c aaa [b] aaaa” => len = 3 + 4 = 7
- if they are not the same, len = max(left, right)
- e.g2. “aa [b] ccc d c” => len = max(2, 3) = 3
- if they are the same, len = left + right
- If the letter occurs more than len times, we can always find an extra one and swap it with the current letter => ++len
- e.g.1, count[“a”] = 9 > 7, len = 7 + 1 = 8
- e.g.2, count[“c”] = 4 > 3, len = 3 + 1 = 4
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
// Author: Huahua class Solution { public: int maxRepOpt1(string text) { int n = text.length(); // Length of repeted substring ends with text[i] vector<vector<int>> len1(n, vector<int>(26)); // Length of repeated substring starts with text[i] vector<vector<int>> len2(n, vector<int>(26)); vector<int> counts(26); int last = -1; // not a letter int l = 0; int ans = 0; for (int i = 0; i < n; ++i) { const int c = text[i] - 'a'; if (c == last) { ++l; } else { last = c; l = 1; } len1[i][c] = l; len2[i - l + 1][c] = l; ++counts[c]; ans = max(ans, l); } for (int i = 1; i < n - 1; ++i) { int cl = text[i - 1] - 'a'; int cr = text[i + 1] - 'a'; int left = len1[i - 1][cl]; int right = len2[i + 1][cr]; int count = 0; if (cl != cr) { // e.g. "c aaa b cccc" => "b aaa ccccc" count = max(left + (counts[cl] > left ? 1 : 0), right + (counts[cr] > right ? 1 : 0)); } else { // e.g. "a c aaa b aaaa" => "b c aaaaaaaa" count = left + right; if (counts[cl] > count) ++count; } ans = max(ans, count); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment