본문 바로가기
LeetCode/Array & Hashing

[LeetCode][Kotlin] 1624. Largest Substring Between Two Equal Characters

by jinwo_o 2024. 10. 18.

1624. Largest Substring Between Two Equal Characters

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.

 

substring is a contiguous sequence of characters within a string.

문자열 s가 주어지면 두 문자를 제외하고 두 개의 동일한 문자 사이에서 가장 긴 부분 문자열의 길이를 반환합니다. 해당 하위 문자열이 없으면 -1을 반환합니다. 

하위 문자열은 문자열 내의 연속적인 문자 시퀀스입니다.

 

Example 1:

Input: s = "aa"

Output: 0

Explanation: The optimal substring here is an empty substring between the two 'a's.

 

Example 2:

Input: s = "abca"

Output: 2

Explanation: The optimal substring here is "bc".

 

Example 3:

Input: s = "cbzxy"

Output: -1

Explanation: There are no characters that appear twice in s.

 

Constraints:

  • 1 <= s.length <= 300
  • s contains only lowercase English letters.

코드 1

class Solution {
    fun maxLengthBetweenEqualCharacters(s: String): Int {
        var answer = -1
        val hs = HashSet<Char>()

        s.forEach { c ->
            if (c !in hs) {
                val start = s.indexOfFirst { it == c }
                val end = s.indexOfLast { it == c }
                answer = maxOf(answer, end - 1 - start)
            }
        }

        return answer
    }
}

 

코드 2

class Solution {
    fun maxLengthBetweenEqualCharacters(s: String): Int {
        var answer = -1
        val hm = HashMap<Char, Int>()

        s.forEachIndexed { i, c ->
            if (c in hm) {
                answer = maxOf(answer, i - 1 - hm[c]!!)
            } else {
                hm[c] = i
            }
        }

        return answer
    }
}