IT/알고리즘
[백준] 균형잡힌 세상 , 쇠막대기
남갯
2024. 11. 4. 21:42
728x90
SMALL
https://www.acmicpc.net/problem/10799
fun main() = with(Scanner(System.`in`)) {
val text = nextLine()
val stack: Stack<Char> = Stack()
var result = 0
var last: Char = ' '
for (i in text.indices) {
when (text[i]) {
'(' -> {
stack.push(text[i])
last = text[i]
}
')' -> {
if (stack.isNotEmpty()) {
stack.pop()
if (last == '(') {
result += stack.size
} else{
result += 1
}
last = text[i]
}
}
}
}
println(result)
}
10퍼센트에서 안돌아가는 이슈
https://www.acmicpc.net/problem/4949
text.split(".").forEach { divide ->
val stack: Stack<Char> = Stack()
var result = true
if (divide.isNotEmpty()) {
divide.forEach {
when (it) {
'(' -> stack.push('(')
'[' -> stack.push('[')
']' -> if (stack.isNotEmpty() && stack.peek() == '[') {
stack.pop()
} else {
result = false
}
')' -> {
if (stack.isNotEmpty() && stack.peek() == '(') {
stack.pop()
} else {
result = false
}
}
}
}
if (result && stack.isEmpty()) {
println("yes")
} else {
println("no")
}
}
}
728x90
LIST