Skip to content

LeetCode: 32. 最长有效括号 #77

Open

Description

@resse92

思路:
用栈来实现,没啥难度

class Solution {
public:
    int longestValidParentheses(string s) {
        int max_len = 0, last = -1; // the position of last '('
        stack<int> lefts;
        
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') {
                lefts.push(i);
            } else {
                if (lefts.empty()) {
                    last = i;
                } else {
                    lefts.pop();
                    if (lefts.empty()) {
                        max_len = max(max_len, i - last);
                    } else {
                        max_len = max(max_len, i - lefts.top());
                    }
                }
            }
        }
        return max_len;
    }
};

Activity

  1. changed the title [-]f[/-] [+]LeetCode: 32. 最长有效括号[/+] on Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions