I, entitled 1
Second, the idea
The establishment of a stack, when traversed all left parenthesis are pushed onto the stack, there is a time right parenthesis appears on top of the stack brackets and determine the current right parenthesis is not a right, yes, then it will pop, or returns false.
When judged as a character input only occurs in "() {} []" of these types, and between two brackets ASCii pairing value greater than zero is less than 3, it can be directly used as the determination condition.
Third, the code
import java.util.ArrayList;
import java.util.List;
public class T0020 {
public static void main(String[] args) {
System.out.println( isValid("[") ); //true
System.out.println( isValid("()[]{}") ); //true
System.out.println( isValid("(]") ); //false
System.out.println( isValid("([)]") ); //false
System.out.println( isValid("{[]}") ); //true
System.out.println( isValid("{{)}") ); //false
}
public static boolean isValid(String s) {
List<Integer> stoke = new ArrayList<Integer>(); //存储还未配对的括号,用于判断
//对字符串进行遍历
for ( char i : s.toCharArray() ){
//如果是左括号就将其压入栈中,右括号就进行对应的处理
if ( i == '(' || i == '{' || i == '[' ){
stoke.add( (int)i );
}else {
//如果栈中已经空了,就返回false
if (stoke.size() == 0 )
return false;
//栈中存储的括号能和当前括号配对就将其出栈,否则返回false
if ( ((int)i - stoke.get(stoke.size()-1)) < 3 && ((int)i - stoke.get(stoke.size()-1)) > 0 ){
stoke.remove(stoke.size()-1);
}else
return false;
}
}
//只有栈中已经空了才返回true
return stoke.size()==0;
}
}
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/valid-parentheses
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎