判断括号字符串是否合法 valid-parentheses

20. Valid Parentheses

Easy

2700136FavoriteShare

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

1. 使用栈结构

/**
 * 使用栈结构
 * @param s
 * @return
 */
public boolean isValid(String s){
     Stack stack = new Stack<>();
     Map map = new HashMap<>();
     char[] chars = s.toCharArray();
     map.put(')','(');
     map.put('}','{');
     map.put(']','[');
     for(int i=0;i < s.length();i++){
         if(!map.containsKey(chars[i])) {
             //为左括号时直接入栈
              stack.push(chars[i]);
             }else{
             //为右括号时,如果栈为空或者栈顶与该括号类型不匹配返回false
              if(stack.empty() || map.get(chars[i]) != stack.pop()){
                  return false;
                  }
             }
         }
     //字符串遍历完毕后,如果栈为空返回true,反之返回false
     return stack.empty();
    }
}

2. 替换法

public boolean isValid(String s){
    int length;
    do{
        length = s.length();
        s = s.replace("()","").replace("[]","").replace("{}","");
    }while(length != s.length());
    return s.length() == 0;
}

你可能感兴趣的:(基础,数据结构与算法,stack)