Sponsored
Sponsored
This approach uses a hash map to store the first and last occurrence of each character as you traverse the string. For each character, calculate the distance between its occurrences and keep track of the maximum distance found. This efficiently provides the length of the longest substring between two identical characters.
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) since the hash map size is constant (fixed at 256 for all possible lowercase characters).
This Python function also employs a dictionary to store character first occurrences. It computes the longest substring by the difference of current and first indices for repeated characters, minus one.
This approach involves two pass-throughs of the string. The first pass records each character's first occurrence, while the second calculates potential maximum lengths using each character's last occurrence.
Time Complexity: O(n).
Space Complexity: O(1).
1#include <iostream>
2#include <unordered_map>
3using namespace std;
4
5int maxLengthBetweenEqualCharacters(string s) {
6 unordered_map<char, int> firstOccurrence;
7 unordered_map<char, int> lastOccurrence;
8 int maxLen = -1;
9 for (int i = 0; i < s.length(); i++) {
10 if (firstOccurrence.find(s[i]) == firstOccurrence.end()) {
11 firstOccurrence[s[i]] = i;
12 }
13 lastOccurrence[s[i]] = i;
14 }
15 for (auto pair : firstOccurrence) {
16 maxLen = max(maxLen, lastOccurrence[pair.first] - pair.second - 1);
17 }
18 return maxLen;
19}
20
21int main() {
22 string s = "abca";
23 int result = maxLengthBetweenEqualCharacters(s);
24 cout << result << endl;
25 return 0;
26}
C++ implementation makes use of two unordered maps for recording first and last occurrences, facilitating the calculation of the longest substring length between identical characters.
Solve with full IDE support and test cases