valid-parentheses
class Solution {
public:
bool isValid(string s) {
if(s.empty())
return true;
stack<char> sStack;
for(size_t i = 0; i < s.size(); ++i) {
if(s[i] == '(')
sStack.push(')');
else if(s[i] == '[')
sStack.push(']');
else if(s[i] == '{')
sStack.push('}');
else if(sStack.empty() || sStack.top() != s[i])
return false;
else
sStack.pop();
}
return sStack.empty();
}
};
longest-valid-parentheses
class Solution {
public:
int longestValidParentheses(string s) {
int ans=0;
stack<int> st;
st.push(-1);
for(int i=0;i<s.size();i++){
if(s[i]=='(') st.push(i);
else{
st.pop();
if(!st.size())
st.push(i);
else
ans=max(ans,i-st.top());
}
}
return ans;
}
};
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push('(');
} else if (!stack.empty() && stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
public int longestValidParentheses(String s) {
int maxlen = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 2; j <= s.length(); j+=2) {
if (isValid(s.substring(i, j))) {
maxlen = Math.max(maxlen, j - i);
}
}
}
return maxlen;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode/
3 generate-parentheses
//链接:https://www.nowcoder.com/questionTerminal/c9addb265cdf4cdd92c092c655d164ca
//left代表左括号剩余个数,right同理
//1.每部递归注意递归体即有几种可选的操作 +'(' or + ')'
//2.考虑操作的限制条件,加右括号时满足左括号的剩余个数<右括号
//3.递归退出条件,左右括号个数都用光即可
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n < 1) return res;
int left = n, right = n;
generateParenthesisDfs(res, left, right, "");
return res;}
void generateParenthesisDfs(vector<string> &res, int left, int right, string cur){
//3.跳出条件
if(left == 0 && right == 0){
res.push_back(cur);
return;//没有循环直接执行。执行完毕后,推出
}
//1.choice
if(left > 0) generateParenthesisDfs(res, left - 1, right, cur + '(');
//2.constrain
if(right > 0 && right > left) generateParenthesisDfs(res, left, right - 1, cur + ')');
}
};