LeetCode 032 Longest Valid Parentheses
2016-05-18 09:45
393 查看
题目要求在由’(‘,’)’组成的字符串中找到最长合法子串,要求子串中括号配对合法。
思路:
合法子串的性质:
如果s是一个合法子串,那”(“+s+”)”也是合法子串。
所以可以用一个布尔数组记录字符串的某位是否属于一个合法子串。在布尔数组中找最长的连续true即可。
实现上,用一个栈记录当前等待配对的左括号位置。扫描整个字符串:
* 如果遇到左括号,把位置入栈。
* 如果遇到右括号:
** 如果栈空 什么都不做
** 否则把当前位置标记为true,把栈顶记录的位置也标记为true,弹出栈顶。
算法的时间复杂度为O(n),n为字符串长度。
思路:
合法子串的性质:
如果s是一个合法子串,那”(“+s+”)”也是合法子串。
所以可以用一个布尔数组记录字符串的某位是否属于一个合法子串。在布尔数组中找最长的连续true即可。
实现上,用一个栈记录当前等待配对的左括号位置。扫描整个字符串:
* 如果遇到左括号,把位置入栈。
* 如果遇到右括号:
** 如果栈空 什么都不做
** 否则把当前位置标记为true,把栈顶记录的位置也标记为true,弹出栈顶。
算法的时间复杂度为O(n),n为字符串长度。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解