반응형
https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - 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
class Solution {
fun isValid(s: String): Boolean {
val stack = Stack<String>()
s.forEach {
val currentBracket = it.toString()
if (currentBracket.isOpenedBracket()) {
stack.push(currentBracket)
} else {
if (stack.isEmpty()) return false
val lastBracket = stack.pop()
if (lastBracket.isClosedBracket() || !currentBracket.isMatchedBracket(lastBracket)) {
return false
}
}
}
return stack.isEmpty()
}
private fun String.isOpenedBracket() = listOf("(", "[", "{").contains(this)
private fun String.isClosedBracket() = listOf(")", "]", "}").contains(this)
private fun String.isMatchedBracket(bracket: String) =
this == "(" && bracket == ")" || this == ")" && bracket == "(" ||
this == "[" && bracket == "]" || this == "]" && bracket == "[" ||
this == "{" && bracket == "}" || this == "}" && bracket == "{"
}
https://github.com/960813/leetcode-problems/commit/013c14fa00a72d643fe416fd0949bd2fd41b62d9
[020] Kotlin · 960813/leetcode-problems@013c14f
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
github.com
반응형
☕️ Networking
기술 직군의 기술적인 교류, 커리어 이야기, 직군 무관 네트워킹 모두 환영합니다!
위클리 아카데미 오픈 채팅방(비밀번호: 9323)
kakaotalk: https://open.kakao.com/o/gyvuT5Yd