Title:
given A string containing just the Characters " (' , ") ' , , '} ' , " [' and
The brackets must close in the correct order, and is all valid but and is not "()" "()[]{}" "(]" "([)]" .
Test Instructions:
Given a string that contains the following characters‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and‘]‘,判断输入的字符串是否有效。
这些括号必须按正确的顺序关闭,"()" and "()[]{}"就是有效的,"(]" and "([)]" 就是无效的。
Algorithm Analysis:
The question is whether the matching parentheses match the legitimate problem, can be implemented by the stack, and the stack is generally used to mark the array. If you encounter a character ( , { and [ , then press it into the stack, if encountered ) , } and ] , you need to determine the top of the stack, see if it matches the parentheses, if the match pops up the top of the stack, otherwise the match is considered illegal, the matching process is terminated directly.
The algorithm flow is as follows:
定义数组栈stack;foreach c in String: if c 为(,{,[ then stack.push(c); if c 为 ), }, ] then 判定stack是否为空和stack.top是否与c相匹配。
AC Code:
public class Solution {private Boolean a;private boolean flag;private int i;private int n;public Boolean isValid (String s) { stack st= new stack ();//Create Stack Object if (s.length ()%2!=0) Flag=false; else { i=0; St.push (S.charat (0)); while (I<s.length ()-1) { if (St.empty ()) { St.push (S.charat (i+1)); i++; } if (St.peek (). toString (). charAt (0) = = ' (' &&s.charat (i+1) = = ') ') | | (St.peek (). toString (). charAt (0) = = ' [' &&s.charat (i+1) = = '] ' ) | | (St.peek (). toString (). charAt (0) = = ' {' &&s.charat (i+1) = = '} ')) { st.pop (); } else St.push (S.charat (i+1)); i++; } Flag=st.empty (); } return flag; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode][java] Valid parentheses