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

    有效字符串需满足:

    1. 左括号必须用相同类型的右括号闭合。
    2. 左括号必须以正确的顺序闭合。

    注意空字符串可被认为是有效字符串。

    示例 1:

    输入: “()” 输出: true

    示例 2:

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

    示例 3:

    输入: “(]” 输出: false

    示例 4:

    输入: “([)]” 输出: false

    示例 5:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-parentheses


    1. class Solution {
    2. public boolean isValid(String s) {
    3. if (s.length()==0 || s.length() == 1){
    4. return false;
    5. }
    6. char first = '(';
    7. char second = '[';
    8. char third = '{';
    9. char first1 = ')';
    10. char second1 = ']';
    11. char third1 = '}';
    12. Deque<Character> linkedList = new LinkedList<>();
    13. int len = s.length();
    14. for (int i = 0; i < len; i++) {
    15. if (s.charAt(i) == first){
    16. linkedList.add(first);
    17. }else if (s.charAt(i) == second){
    18. linkedList.add(second);
    19. }else if (s.charAt(i) == third){
    20. linkedList.add(third);
    21. }else if (s.charAt(i) == first1 && linkedList.size() != 0 && linkedList.getLast() == first){
    22. linkedList.removeLast();
    23. }else if (s.charAt(i) == second1 && linkedList.size() != 0 && linkedList.getLast() == second){
    24. linkedList.removeLast();
    25. }else if (s.charAt(i) == third1 && linkedList.size() != 0 && linkedList.getLast() == third){
    26. linkedList.removeLast();
    27. }else if (s.charAt(i) == first1 && (linkedList.size() == 0 || linkedList.getLast() == second || linkedList.getLast() == third)){
    28. return false;
    29. }else if (s.charAt(i) == second1 && (linkedList.size() == 0 || linkedList.getLast() == first || linkedList.getLast() == third)){
    30. return false;
    31. }else if (s.charAt(i) == third1 && (linkedList.size() == 0 || linkedList.getLast() == first || linkedList.getLast() == second)){
    32. return false;
    33. }
    34. }
    35. return linkedList.size() == 0;
    36. }
    37. }