Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
resse92 opened this issue May 29, 2018 · 0 comments
Open

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

resse92 opened this issue May 29, 2018 · 0 comments

Comments

@resse92
Copy link
Owner

resse92 commented May 29, 2018

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

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;
    }
};
@resse92 resse92 changed the title f LeetCode: 32. 最长有效括号 Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant