1、有效的括号
class Solution {
public boolean isValid(String s) {
if(s.length() % 2 == 1) return false;
Stack<Character> stack = new Stack<Character>();
for(int i=0; i<s.length(); i++){
if((s.charAt(i) == '(') || (s.charAt(i) == '[') || (s.charAt(i) == '{'))
stack.push(s.charAt(i));
if(!stack.isEmpty()){
if(((stack.peek() == '(') && (s.charAt(i) == ')')) || ((stack.peek() == '[') && (s.charAt(i) == ']')) || ((stack.peek() == '{') && (s.charAt(i) == '}')))
stack.pop();
}
}
return stack.size() == 0;
}
}
2、括号生成
class Solution {
List<String> result = new ArrayList<String>();
public List<String> generateParenthesis(int n) {
backtrack(new String(), 0, 0, n);
return result;
}
public void backtrack(String cur, int open, int close, int max){
if(cur.length() == max*2){
result.add(cur);
return ;
}
if(open < max){
backtrack(cur+"(", open+1, close, max);
}
if(close < open){
backtrack(cur+")", open, close+1, max);
}
}
}
3、最长有效括号
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
int result = 0;
for(int i=0; i<s.length(); i++){
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if(!stack.empty()) stack.pop();
if (stack.empty()) {
stack.push(i);
} else {
result = Math.max(result, i - stack.peek());
}
}
}
return result;
}
}
4、根据二叉树创建字符串
/**
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public StringBuilder result = new StringBuilder();
public String tree2str(TreeNode t) {
dfs(t);
return new String(result);
}
public void dfs(TreeNode current){
if(current == null) return;
result.append(current.val);
if(current.left == null && current.right == null)
return;
else{
result.append("(");
dfs(current.left);
result.append(")");
if(current.right != null){
result.append("(");
dfs(current.right);
result.append(")");
}
}
}
}
5、删除最外层括号
class Solution {
public String removeOuterParentheses(String S) {
int count = 0, start = 0;
StringBuilder result = new StringBuilder();
for(int i=0; i<S.length(); i++){
if(S.charAt(i) == '(')
count++;
if(S.charAt(i) == ')')
count--;
if(count == 1 && S.charAt(i) == '(')
start = i;
if(count == 0)
result.append(S.substring(start+1, i));
}
return result.toString();
}
}
6、使有效的括号添加最少
class Solution {
public int minAddToMakeValid(String S) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
bal += S.charAt(i) == '(' ? 1 : -1;
if (bal == -1) {
ans++;
bal++;
}
}
return ans + bal;
}
}