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).
1import java.util.HashMap;
2
3public class MaxLengthBetweenEqualCharacters {
4 public int maxLengthBetweenEqualCharacters(String s) {
5 HashMap<Character, Integer> firstOccurrence = new HashMap<>();
6 int maxLen = -1;
7 for (int i = 0; i < s.length(); i++) {
8 char c = s.charAt(i);
9 if (!firstOccurrence.containsKey(c)) {
10 firstOccurrence.put(c, i);
11 } else {
12 maxLen = Math.max(maxLen, i - firstOccurrence.get(c) - 1);
13 }
14 }
15 return maxLen;
16 }
17
18 public static void main(String[] args) {
19 MaxLengthBetweenEqualCharacters solution = new MaxLengthBetweenEqualCharacters();
20 System.out.println(solution.maxLengthBetweenEqualCharacters("abca"));
21 }
22}
In this Java solution, a HashMap is used to record each character's first occurrence, allowing the calculation of maximum length for valid substrings between identical characters.
Java approach uses two HashMaps for tracking first and last occurrences, allowing accurate measurement of maximum substring lengths between character pairs.