[LeetCode] Largest Substring Between Two Equal Characters

1624. Largest Substring Between Two Equal Characters

Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.

A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxLengthBetweenEqualCharacters(string s) {
vector<int> freq(26,-1);
int res = -1;
for(int i = 0; i < s.length(); i++) {
int x = s[i] - 'a';
if(freq[x] == -1) freq[x] = i;
else res = max(res, i - freq[x] - 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/31/PS/LeetCode/largest-substring-between-two-equal-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.