3090. Maximum Length Substring With Two Occurrences
</> Solution
/**
* Problem: LeetCode 3090 - Maximum Length Substring With Two Occurrences
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int maximumLengthSubstring(String s) {
int n = s.length();
int[] freq = new int[26];
int left = 0;
int maxLen = 0;
for (int right = 0; right < n; right++) {
int c = s.charAt(right) - 'a';
freq[c]++;
while (freq[c] > 2) {
freq[s.charAt(left) - 'a']--;
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}
"""
Problem: LeetCode 3090 - Maximum Length Substring With Two Occurrences
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
freq = [0] * 26
left = 0
max_len = 0
for right, ch in enumerate(s):
c = ord(ch) - ord('a')
freq[c] += 1
while freq[c] > 2:
freq[ord(s[left]) - ord('a')] -= 1
left += 1
max_len = max(max_len, right - left + 1)
return max_len
/**
* Problem: LeetCode 3090 - Maximum Length Substring With Two Occurrences
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 3090 - Maximum Length Substring With Two Occurrences
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int maximumLengthSubstring(string s) {
int n = s.length();
vector<int> freq(26, 0);
int left = 0;
int maxLen = 0;
for (int right = 0; right < n; right++) {
int c = s[right] - 'a';
freq[c]++;
while (freq[c] > 2) {
freq[s[left] - 'a']--;
left++;
}
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}
};
/**
* Problem: LeetCode 3090 - Maximum Length Substring With Two Occurrences
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
var maximumLengthSubstring = function(s) {
const n = s.length;
const freq = new Int32Array(26);
let left = 0;
let maxLen = 0;
for (let right = 0; right < n; right++) {
const c = s.charCodeAt(right) - 97;
freq[c]++;
while (freq[c] > 2) {
freq[s.charCodeAt(left) - 97]--;
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
};