leetcode-20

Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.

Valid string must meet:

Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.

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

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.

 

public class Solution20 {
    Map<Character, Character> mappings = new HashMap<>();
    Stack<Character> stack = new Stack<>();
    public boolean isValid(String s) {
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(mappings.containsKey (C)) {
                 char Top = stack.empty () '#'? : stack.pop ();
                 IF (! = Top mappings.get (C)) {
                     return  to false ; 
                } 
            } the else { 
                Stack. Push (C); 
            } 
        } 
        // here to be noted that a place is "[" this 
        return stack.isEmpty (); 
    } 
}

end, examine the stack and use the last comment of place

Guess you like

Origin www.cnblogs.com/CherryTab/p/12104653.html