
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int res=0;
for(int i=0;i<s.size();++i){
if(s[i]=='('){
st.push(i);
}else{
st.pop();
if(st.empty()){
st.push(i);
}else{
res=max(res,i-st.top());
}
}
}
return res;
}
本文介绍了一种使用栈实现的高效算法,用于寻找字符串中具有最长有效括号子串的长度。通过遍历输入字符串并利用栈来跟踪左括号的位置,算法能够巧妙地计算出最长的有效括号对。该方法不仅简洁而且易于理解。
522

被折叠的 条评论
为什么被折叠?



