问题:给定一个只包含 "(" 和 ")" 的字符串,寻找其括号配对的最长子串,输出其长度
示例:
输入:"())" 输出:2
输入:"(()()()(" 输出:6
解决思路:利用栈来解决,遍历索引进行压栈和弹栈,最后栈中只剩下没有配对成功的索引位置,配对成功的子串长度记为栈中的相邻元素之差减1
Python代码:
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ if not s: return 0 stack = [] for i in range(len(s)): if not stack or s[i] == "(": stack.append(i) else: if s[stack[-1]] == "(": stack.pop() else: stack.append(i) stack = [-1]+stack+[len(s)] longest = 0 for i in range(len(stack)-1): length = stack[i+1]-stack[i]-1 if longest < length: longest = length return longest