欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

20.Valid Parentheses

程序员文章站 2024-03-22 16:18:58
...
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> characterStack = new Stack<>();
        int len = s.length();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');
        for(int i = 0; i < len; ++i) {
            if( characterStack.isEmpty()) {
                characterStack.push(s.charAt(i));
                continue;
            }
            Character c = s.charAt(i);
            Character t = characterStack.peek();
            if(t == map.get(c)) characterStack.pop();
            else characterStack.push(c);
        }
        return characterStack.isEmpty();
    }
//
//    public static void main(String[] args) {
//        Solution solution = new Solution();
//        System.out.println(solution.isValid("()"));
//    }
}