엔지니어 게시판
LeetCode 솔루션 분류

[5/24] 32. Longest Valid Parentheses

컨텐츠 정보

본문

[LeetCode 시즌 3] 2022년 5월 24일 문제입니다.

https://leetcode.com/problems/longest-valid-parentheses/


32. Longest Valid Parentheses
Hard
8384282Add to ListShare

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

 

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

 

Constraints:

  • 0 <= s.length <= 3 * 104
  • s[i] is '(', or ')'.

관련자료

댓글 1

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 3 ms, faster than 89.02% of C++ online submissions for Longest Valid Parentheses.
Memory Usage: 7.4 MB, less than 42.64% of C++ online submissions for Longest Valid Parentheses.
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int n = s.size();
        int maxLen = 0;
        
        st.push(-1);
        for (int i = 0; i < n; ++i) {
            if (s[i] == '(') st.push(i);
            else {
                st.pop();
                if (st.empty()) st.push(i);
                else maxLen = max(maxLen, i - st.top());
            }
        }
        return maxLen;
    }
};
전체 396 / 9 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0