[leetcode] 784. Letter Case Permutation

반응형

문제

 

 


풀이

기본적으로 탐색하는 character가 문자면 소문자, 대문자로 변환하고 숫자면 다음 character로 넘어갔다.

마지막까지 완료하면 새로운 문자열을 반환하였다.

개념을 그림으로 표현해봤다.

주어진 문자열이 "a1b2" 이면 결과로 ["a1b2", "a1B2", "A1b2", "A1B2"] 가 반환된다.

dfs 함수를 만들고 character가 문자면 두 갈래(소문자, 대문자)로 나눠서 계속 함수를 호출해 풀었다.

 


코드

class Solution {
    fun letterCasePermutation(s: String): List<String> {
        val result = arrayListOf<String>()
        dfs(s.toCharArray(), 0, result)

        return result
    }

    fun dfs(target: CharArray, index: Int, result: ArrayList<String>) {
        if (index > target.lastIndex) {
            result.add(String(target))
        } else {
            if (target[index].isDigit()) {
                dfs(target, index + 1, result)
            } else {
                target[index] = target[index].toLowerCase()
                dfs(target, index + 1, result)

                target[index] = target[index].toUpperCase()
                dfs(target, index + 1, result)
            }
        }
    }
}

 

 

 


참고