SW Test/Programmers

[Programmers] Lv2. ๊ด„ํ˜ธ ํšŒ์ „ํ•˜๊ธฐ(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 9. 23. 17:36
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

 

 

์˜ˆ์‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

 

 

ํ’€์ด

  • Stack์„ ์ด์šฉํ•œ ๋Œ€ํ‘œ์ ์ธ ๋ฌธ์ œ์ธ ๊ด„ํ˜ธ ์ฐพ๊ธฐ์ž…๋‹ˆ๋‹ค.
  • Stack ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” kotlin์— ์—†๊ธฐ์— Java Util ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— ํฌํ•จ๋œ Stack์„ ์ด์šฉํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
import java.util.*

class Solution {
    fun solution(s: String): Int {
        var answer: Int = 0
        var tempStr = s
        
        first@ (1..s.length).forEach{
            tempStr = tempStr.substring(1, tempStr.length) + tempStr.first()
            
            val stack = Stack<Char>()
            for(ch in tempStr){
                if(stack.size == 0){
                    stack.add(ch)
                }else{
                    if(ch in arrayOf('[','{','(')){
                        stack.add(ch)
                    }else{
                        if(stack.peek() == '[' && ch == ']'){
                            stack.pop()
                        }else if(stack.peek() == '{' && ch == '}'){
                            stack.pop()
                        }else if(stack.peek() == '(' && ch == ')'){
                            stack.pop()
                        }else{
                            break;
                        }
                    }
                }
            }
            
            if(stack.isEmpty()) answer++
        }
        return answer
    }
}

 

 

 

 

๋ฐ˜์‘ํ˜•