leetcode Longest Valid Parentheses
The stack has to record the last position of '('. If matching, The position of ')' - the position of '(' + 1 is the answer since the parentheses between them have been eliminated.class Solution { public: int longestValidParentheses(string s) { // Note: The Solution object is instantiated only once and is reused by each test case. stack<int> sta; int i = 0, j = 0, maxV = 0, count = 0; for (i = 0; i < s.length(); ++i) { if (s[i] == '(') sta.push(i); else { if (!sta.empty() && s[sta.top()] == '(') { sta.pop(); if (sta.empty()) count = i + 1; else count = i - sta.top(); if (count > maxV) maxV = count; } else sta.push(i); } } return maxV; } };
补充:软件开发 , C++ ,