[LeetCode-interview algorithm classic-Java implementation] [020-Valid Parentheses (bracket verification)],-javaparentheses
[020-Valid Parentheses (bracket verification )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "() [] {}" are all valid but "(]" and "([)]" are not.
Theme
Specify a string that only contains (',') ',' {','} ',' [', and'] 'to verify whether the string is valid. Parentheses must be paired and in the correct order.
Solutions
Use a stack to process the input parenthesis string. If the left bracket is used, it is written into the stack. If the right bracket is used, it is associated with the top element of the stack to check whether a pair of parentheses is formed, and process the parentheses of the next input. If they do not match, the result is returned directly.
Code Implementation
import java.util.*;public class Solution { public boolean isValid(String s) { Deque<Character> stack = new LinkedList<>(); int index = 0; Character top; while (index < s.length()) { Character c = s.charAt(index); switch (c) { case '(': case '[': case '{': stack.addFirst(c); break; case ')': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '(') { stack.removeFirst(); } else if (top == '[' || top == '{') { return false; } else { stack.addFirst(c); } break; case ']': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '[') { stack.removeFirst(); } else if (top == '(' || top == '{') { return false; } else { stack.addFirst(c); } break; case '}': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '{') { stack.removeFirst(); } else if (top == '[' || top == '(') { return false; } else { stack.addFirst(c); } break; default: return false; } index++; } return stack.isEmpty(); }}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting at http://blog.csdn.net/derrantcm/article/details/46997247]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.