Longest Valid Parentheses

描述

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

分析

使用栈

  1. // Longest Valid Parenthese
  2. // 使用栈,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. int longestValidParentheses(const string& s) {
  6. int max_len = 0, last = -1; // the position of the last ')'
  7. stack<int> lefts; // keep track of the positions of non-matching '('s
  8. for (int i = 0; i < s.size(); ++i) {
  9. if (s[i] =='(') {
  10. lefts.push(i);
  11. } else {
  12. if (lefts.empty()) {
  13. // no matching left
  14. last = i;
  15. } else {
  16. // find a matching pair
  17. lefts.pop();
  18. if (lefts.empty()) {
  19. max_len = max(max_len, i-last);
  20. } else {
  21. max_len = max(max_len, i-lefts.top());
  22. }
  23. }
  24. }
  25. }
  26. return max_len;
  27. }
  28. };

Dynamic Programming, One Pass

  1. // Longest Valid Parenthese
  2. // 两遍扫描,时间复杂度O(n),空间复杂度O(1)
  3. // @author 曹鹏(http://weibo.com/cpcs)
  4. class Solution {
  5. public:
  6. int longestValidParentheses(const string& s) {
  7. int result = 0, depth = 0, start = -1;
  8. for (int i = 0; i < s.size(); ++i) {
  9. if (s[i] == '(') {
  10. ++depth;
  11. } else {
  12. --depth;
  13. if (depth < 0) {
  14. start = i;
  15. depth = 0;
  16. } else if (depth == 0) {
  17. result = max(result, i - start);
  18. }
  19. }
  20. }
  21. depth = 0;
  22. start = s.size();
  23. for (int i = s.size() - 1; i >= 0; --i) {
  24. if (s[i] == ')') {
  25. ++depth;
  26. } else {
  27. --depth;
  28. if (depth < 0) {
  29. start = i;
  30. depth = 0;
  31. } else if (depth == 0) {
  32. result = max(result, start - i);
  33. }
  34. }
  35. }
  36. return result;
  37. }
  38. };

两遍扫描

  1. // Longest Valid Parenthese
  2. // 两遍扫描,时间复杂度O(n),空间复杂度O(1)
  3. // @author 曹鹏(http://weibo.com/cpcs)
  4. class Solution {
  5. public:
  6. int longestValidParentheses(const string& s) {
  7. int result = 0, depth = 0, start = -1;
  8. for (int i = 0; i < s.size(); ++i) {
  9. if (s[i] == '(') {
  10. ++depth;
  11. } else {
  12. --depth;
  13. if (depth < 0) {
  14. start = i;
  15. depth = 0;
  16. } else if (depth == 0) {
  17. result = max(result, i - start);
  18. }
  19. }
  20. }
  21. depth = 0;
  22. start = s.size();
  23. for (int i = s.size() - 1; i >= 0; --i) {
  24. if (s[i] == ')') {
  25. ++depth;
  26. } else {
  27. --depth;
  28. if (depth < 0) {
  29. start = i;
  30. depth = 0;
  31. } else if (depth == 0) {
  32. result = max(result, start - i);
  33. }
  34. }
  35. }
  36. return result;
  37. }
  38. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/stack-and-queue/stack/longest-valid-parentheses.html