Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
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
/**
* 采用栈的方式
* @param s
* @return
*/
public static boolean isValid1(String s)
{
if(s == null || s.length() == 0) return true;
Map<String,String> map = new HashMap<>();
map.put(")","(");
map.put("]","[");
map.put("}","{");
int len = s.length();
Stack<String> stack = new Stack<>();
for(int i = 0; i < len;i++)
{
String key = s.substring(i,i+1);
String value = map.get(key);
if(!stack.contains(value))
{
stack.push(key);
}
else {
stack.pop();
}
}
return stack.isEmpty();
}
/**
* 通过不断的替换
* @param s
* @return
*/
public static boolean isValid2(String s)
{
int len = 0;
do {
len = s.length();
s = s.replace("()","").replace("[]","").replace("{}","");
}while(len != s.length());
return s.length() == 0;
}