forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1624-largest-substring-between-two-equal-characters.kt
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
kotlin/1624-largest-substring-between-two-equal-characters.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
class Solution { | ||
fun maxLengthBetweenEqualCharacters(s: String): Int { | ||
val charIndex = HashMap<Char, Int>() | ||
var res = -1 | ||
|
||
for ((i, c) in s.withIndex()) { | ||
if (c in charIndex) | ||
res = maxOf(res, i - charIndex[c]!! - 1) | ||
else | ||
charIndex[c] = i | ||
} | ||
|
||
return res | ||
} | ||
} | ||
|
||
// Similar but slightly different way | ||
class Solution { | ||
fun maxLengthBetweenEqualCharacters(s: String): Int { | ||
val letters = Array (26) { intArrayOf(302, -302) } | ||
var res = -1 | ||
for (l in letters.indices) { | ||
for ((i, c) in s.withIndex()) { | ||
if (c == ('a' + l)) { | ||
letters[l][0] = minOf(letters[l][0], i) | ||
letters[l][1] = maxOf(letters[l][1], i) | ||
res = maxOf(res, letters[l][1] - letters[l][0] - 1) | ||
} | ||
} | ||
} | ||
|
||
return res | ||
} | ||
} |