1. class Solution {
    2. public boolean isValid(String s) {
    3. /**
    4. 思路1:暴力求解
    5. 1.对字符串中的'{}','()','[]'做遍历替换
    6. 思路2:借助栈来求解
    7. 1.遍历字符串,每次都压入栈,压入栈时和栈顶元素做等值匹配
    8. 2.当第一次出现栈顶元素和遍历到的元素不匹配的时候,直接返回false
    9. 3.最终判断栈中是否还有元素,如果没有元素则为true,如果还有元素,则为false
    10. */
    11. if(s.isEmpty())
    12. return true;
    13. Stack<Character> stack=new Stack<Character>();
    14. for(char c:s.toCharArray()){
    15. if(c=='(')
    16. stack.push(')');
    17. else if(c=='{')
    18. stack.push('}');
    19. else if(c=='[')
    20. stack.push(']');
    21. else if(stack.empty()||c!=stack.pop())
    22. return false;
    23. }
    24. if(stack.empty())
    25. return true;
    26. return false;
    27. }
    28. }