fun stringContainsValidParentheses(s: String): Boolean {
val stack = mutableListOf<Char>() // Stack implemented using a mutable list
for (ch in s) {
when (ch) {
'(' -> stack.add(')')
'{' -> stack.add('}')
'[' -> stack.add(']')
')', '}', ']' -> {
if (stack.isEmpty() || stack.removeAt(stack.size - 1) != ch) {
return false
}
}
}
}
// Return true if the stack is empty, indicating valid parentheses
return stack.isEmpty()
}
fun main() {
println(stringContainsValidParentheses("(){}[]"))
println(stringContainsValidParentheses("([{}])"))
println(stringContainsValidParentheses("(){}[]()(){}"))
println(stringContainsValidParentheses("(]"))
println(stringContainsValidParentheses("({[)]}"))
}
/*
run:
true
true
true
false
false
*/