Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Using hashmap
To solve the problem of finding the length of the longest substring between two equal characters in the given string s
, we need to consider the following points:
-
Identifying Equal Characters:
- We need to track the first occurrence of each character as we traverse the string.
- For each character encountered, check if it has appeared before.
-
Calculating the Length of Substrings:
- If the character has appeared before, calculate the length of the substring between the first occurrence and the current position, excluding the two characters themselves.
- Update the maximum length found so far.
-
Return the Result:
- If no such substrings exist, return
-1
. Otherwise, return the maximum length found.
- If no such substrings exist, return
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the strings
. This is because we traverse the string linearly once. - 🧺 Space complexity:
O(n)
for storing the first occurrence of characters since we use a fixed-size array.