objectLongestValidParentheses{ defmain(args: Array[String]): Unit = { println(longestValidParentheses("(()")) println(longestValidParentheses(")()())")) }
/** * 暴力解法, 前后两个指针判断是否为有效括号 */ deflongestValidParentheses(str: String): Int = { if (str.length < 2) return0 var res = 0
val stack = new java.util.Stack[Char]() for (i <- 0 until str.length - 1) { if (str.charAt(i) == '(') { stack.clear() stack.push(str.charAt(i)) breakable(for (j <- i + 1 until str.length) { if (str.charAt(j) == '(') { stack.push('(') } else { if (!stack.isEmpty) { stack.pop() if (stack.isEmpty()) { res = Math.max(res, j - i + 1) } } else { break() } } }) } } res }
deflongestValidParentheses2(str: String): Int = { if (str.length < 2) return0 var res = 0