【20 Questions】Effective parentheses

1. Topic introduction

Valid parentheses for Leetcode 20: https://leetcode.cn/problems/valid-parentheses/

insert image description here

2. Problem-solving ideas

This question mainly uses the knowledge of hash tables and stacks. You need to be very familiar with how to use hashes and stacks in Java.

3. Complete code

Note: The following code is a complete code that can be used for self-testing. To upload the ac part of Likou, just paste the isValid function.

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class Solution {
    
    

	public static void main(String[] args) {
    
    
		Solution obj = new Solution();
		boolean res = obj.isValid("(()())");
		System.out.println(res);
	}
	
	public boolean isValid(String s) {
    
    
		int n = s.length();
		if(n%2==1) {
    
    
			return false;
		}
		
		Map<Character,Character>map = new HashMap<Character,Character>();
		map.put(')', '(');
		map.put('}', '{');
		map.put(']', '[');
		
		Deque<Character>stack = new LinkedList<Character>();
		for(int i=0;i<s.length();i++) {
    
    
			char ch = s.charAt(i);
			if(map.containsKey(ch)) {
    
    
				if(stack.isEmpty()||stack.peek()!=map.get(ch)) {
    
    
					return false;
				}
				stack.pop();
			}else {
    
    
				stack.push(ch);
			}
		}
		return stack.isEmpty();
    }
}

Guess you like

Origin blog.csdn.net/qq_40968179/article/details/130397001