有效的括号&&最长有效括号

有效括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: “()”
输出: true
示例 2:

输入: “()[]{}”
输出: true

class Solution {
    public boolean isValid(String s) {

        Stack <Character> stack=new Stack();

        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='('){
                stack.push(')');
            }else if(s.charAt(i)=='['){
                stack.push(']');
            }else if(s.charAt(i)=='{'){
                stack.push('}');
            }else if(s.charAt(i)==')'){
                if(!stack.isEmpty()&&stack.peek()==')'){
                    stack.pop();
                }else{
                    stack.push(')');
                }
            }else if(s.charAt(i)==']'){
                if(!stack.isEmpty()&&stack.peek()==']'){
                    stack.pop();
                }else{
                    stack.push(']');
                }
            }else if(s.charAt(i)=='}'){
                if(!stack.isEmpty()&&stack.peek()=='}'){
                    stack.pop();
                }else{
                    stack.push('}');
                }
            }
        }
        return stack.isEmpty();

    }
}

最长有效括号

给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。

  • 先将-1放进去;
  • 遇到( 将他的下标放进去;否则pop;若为空则将i放进去;
  • 然后maxlen = Math.max(maxlen, (i - q.peek()));;
import java.util.*;
class Solution {
public int longestValidParentheses(String s) {
    Stack<Integer> q = new Stack();
		q.push(-1);
		int maxlen=0;
		for (int i = 0; i < s.length(); i++) {
			if(s.charAt(i)=='(') {
				q.push(i);
			}else {
				q.pop();
				if(q.size()==0) {
					q.push(i);
				}else {
					maxlen = Math.max(maxlen, (i - q.peek()));
				}
			}
		}
		System.out.println(maxlen);
		return maxlen;
    }
}

你可能感兴趣的:(数组&位运算&堆栈)