Algorithms/- LeetCode

LeetCode - 392. Is Subsequence [Kotlin]

자굿 2022. 9. 10. 03:51
 

Is Subsequence - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

정답(Solution)

class Solution {
    fun isSubsequence(s: String, t: String): Boolean {
        var sIndex = 0
        for(i in 0 until t.length){
            if(sIndex < s.length && s[sIndex] == t[i]){
                sIndex++
            }
        }
        
        return if(sIndex == s.length)
            true
        else
            false
    }
}

 

분석

  • 필요없는 변수를 제거하고 return 에 식을 사용하여 when을 대체

 

참고할 만한 정답

class Solution {
    fun isSubsequence(t: String, s: String): Boolean {
        // o(ns)
        var tIdx = 0
        var sIdx = 0
        if(t.isEmpty()) return true
        
        while(sIdx < s.length && tIdx < t.length) {
            
            if(s.get(sIdx) == t.get(tIdx)) {
                if(tIdx == t.length -1) {
                    return true
                }
                tIdx++
                
            }
            sIdx++
        }
        return false
    }
}

분석

  • while문을 사용하여 풀이

 

초기 정답(Initial Solution)

class Solution {
    fun isSubsequence(s: String, t: String): Boolean {
        var sIndex = 0
        var check = 0
        for(i in 0 until t.length){
            if(sIndex < s.length && s[sIndex] == t[i]){
                check++
                sIndex++
            }
        }
        
        when{
            check == s.length -> return true
            else -> return false
        }
    }
}

분석

  • 2개의 index를 사용하여 s의 문자들을 순차적으로 비교하며 모두 일치할 경우 true를 리턴
  • s의 index는 s의 length 보다 작아야 한다.
반응형