Leetcode (Question 20: Valid Parentheses)

This is an issue, sharing the solution to a simple problem  about Likou

topic:

Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

An opening parenthesis must be closed with a closing parenthesis of the same type.
Opening parentheses must be closed in the correct order.
 

Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
Example 4:

Input: s = "([)]"
Output: false
Example 5:

Input: s = "{[]}"
Output: true
 

hint:

1 <= s.length <= 104
s consists only of brackets '()[]{}'

Source: LeetCode
Link: https://leetcode.cn/problems/valid-parentheses
Copyright belongs to LeetCode Network. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

When I first saw this topic, my brain became hot and I wrote the following code

 

 However, after execution, I found a problem. {)}, (()[) and other situations actually return true. Now my brain is buzzing, and I realize that it is not so simple; after some contemplation, I thought of a new idea .

 

That is: create a code like this to replace the if-else judgment of the previous assignment

public static boolean choose(char c) {         //If it is the first half, return true         if( c=='(' || c=='[' || c=='{' ) {             return true;         }         return false;     } 





 Then add the characters that can make a pair to a HashMap<Character,Character> collection , and create a stack , push the characters that match the left half of the above into the stack, and when traversing to the right half, if the stack is not empty , pop up one on the top of the stack to see if it matches the key-value pair in the hash table, and if it matches, continue traversing; when the traversal is not over, it encounters the right half and the stack is empty and the key-value pair does not match , it will directly return false (I admit that there are billions of twists and turns here, I suggest reading it several times).

It is not necessarily correct to be able to go to the end of the traversal. It also depends on whether the count stack is empty. If it is empty, it is right, otherwise it is wrong.

The following is the solution code:

class Solution {
    public boolean isValid(String s) {
      
    HashMap<Character,Character> map=new HashMap<Character, Character>();
		//先将能凑成一对的,添加到集合中
        map.put('(',')');
		map.put('{','}');
		map.put('[',']');
		  int len=s.length();//得到字符串的长度
		Stack<Character> stack=new Stack<Character>();//创建一个栈,来装([{
		
		for( int i = 0 ; i < len ; i++) {
			char c=s.charAt(i);//将字符串分解为一个个字符

            //如果是前半段,则压到栈中
			if(choose(c)) {
				stack.push(c);
			}else {
                //如果是后半段,先查看此时栈中是否还有值,如果没有了,则返回false
                if(stack.isEmpty()){
                    return false;
                }

                //查看栈顶的元素,如果不能与后半段匹配,则就错了
				if(map.get(stack.peek())!=c){
					return false;
				}else {//如果匹配成功,就将栈顶元素弹出去
					stack.pop();
				}				
			}
		}
		return stack.isEmpty()?true:false;//如果循环结束了,栈为空则true,否则为false
	}
    //这里做了一个方法,替换掉前面一大堆的if-else判断
	public static boolean choose(char c) {
        //如果是前半段,则返回true
		if(  c=='(' || c=='[' || c=='{' ) {
			return true;
		}
		return false;
	} 
}

Thank you for reading it!

Guess you like

Origin blog.csdn.net/m0_62780474/article/details/125075002