就是做个扫描,能匹配的算下多长,如果不能匹配.就继续从后开始.
class Solution { public: int longestValidParentheses(string s) { stack<int> st; int last = -1; int maxlen = 0; for(int i = 0 ; i < s.size() ; i++) { if(s[i] == '(') st.push(i); else{ if(st.empty()){ last = i; }else{ st.pop(); if(st.empty()){ maxlen = max(maxlen , i - last); }else{ maxlen = max(maxlen , i - st.top()); } } } } return maxlen; } };
by 1957