코테준비 - Longest Valid Parentheses

정상화·2023년 2월 26일

LeetCode

목록 보기
30/222

Longest Valid Parentheses

class Solution {
public:
    int longestValidParentheses(string s) {
        int maxLen = 0;
        unsigned strLen = s.length();
        stack<int> pos;
        pos.push(-1);

        for (unsigned i = 0; i < strLen; i++) {
            if (s.at(i) == '(') {
                pos.push(i);
            } else if (pos.size() > 1) {
                pos.pop();
                int start = pos.top();

                int len = i - start;
                if (maxLen < len) maxLen = len;
            } else {
                pos.top() = i;
            }
        }

        return maxLen;
    }
};
profile
백엔드 희망

0개의 댓글