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).
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MaxLengthBetweenEqualCharacters(string s) {
6 Dictionary<char, int> firstOccurrence = new Dictionary<char, int>();
7 int maxLen = -1;
8 for (int i = 0; i < s.Length; i++) {
9 if (!firstOccurrence.ContainsKey(s[i])) {
10 firstOccurrence[s[i]] = i;
11 } else {
12 maxLen = Math.Max(maxLen, i - firstOccurrence[s[i]] - 1);
13 }
14 }
15 return maxLen;
16 }
17
18 public static void Main(string[] args) {
19 Solution sol = new Solution();
20 Console.WriteLine(sol.MaxLengthBetweenEqualCharacters("abca"));
21 }
22}
This C# solution uses a Dictionary to track first indexes of characters in the string, aiding to compute longest substring length between identical characters.
Java approach uses two HashMaps for tracking first and last occurrences, allowing accurate measurement of maximum substring lengths between character pairs.