TIL #25

loci·2024년 5월 25일
0

TIL

목록 보기
24/103

옹알이 (2)

문자열 배열에서 해당 요소를 특정 문자열들로 만들수있다면 카운트해준다.

단순히 겹치는 문자열만 체크하면 쉽게 풀릴 줄 알았지만 문제는 연속된 문자는 제외해야 했다.


나의 풀이

class Solution {
    fun solution(babbling: Array<String>): Int {
        var answer: Int = 0
        for ( i in babbling){
            var temp = i
            temp = temp.replace("aya", "")
            temp = temp.replace("ye", "")
            temp = temp.replace("woo", "")
            temp = temp.replace("ma", "")
            if(temp == ""){
                answer++
            }
            println(temp)
        }
        return answer
    }
}

연속된 문자열을 체크해주어야 해서 수정

class Solution {
    fun solution(babbling: Array<String>): Int {
        var answer: Int = 0
        for ( i in babbling){
            var temp = i
            var count = 0
            temp = temp.replace("aya", "1")
            temp = temp.replace("ye", "2")
            temp = temp.replace("woo", "3")
            temp = temp.replace("ma", "4")
            
            for( j in 0..temp.length-2){
                if( temp[j] == temp[j+1]){
                    count = 1
                }
            }
            
            temp = temp.replace("1", "")
            temp = temp.replace("2", "")
            temp = temp.replace("3", "")
            temp = temp.replace("4", "")
            
            if(temp == "" && count == 0){
                answer++
            }
            
        }
        return answer
    }
}

문자열의 현재 인덱스와 다음 인덱스와 같은지 비교해 같으면 연속된 문자열로 판단해 제외 시키는 부분 추가


다른사람의 풀이

class Solution {
    fun solution(babbling: Array<String>): Int {
        var answer: Int = 0
        var regex = "aya|ye|woo|ma".toRegex()
        var regexC = "ayaaya|yeye|woowoo|mama".toRegex()
        answer = babbling
        	.map{it.replace(regexC,"*")}
        	.map{it.replace(regex,"")}
        	.filter { it =="" }
        	.size
        
        return answer
    }
}
profile
편리한 개발자

0개의 댓글