Topic:
Given A string containing just the characters‘(‘
,‘)‘
,‘{‘
,‘}‘
,‘[‘
and‘]‘
, determine if the input string is valid.
The brackets must close in the correct order,"()"
and"()[]{}"
is all valid but"(]"
and"([)]"
is not.
Translation:
Give a string to determine if the parentheses match successfully.
Ideas:
With a word Fu Yi, read to a character when judged, if the top of the stack and the current character is satisfied with the left and right brackets matching, then pop, otherwise press the stack.
If the last stack is empty, the match succeeds.
Code:
public static Boolean isValid (String s) {if (s.length () = = 0) return true; Stack<character> st = New Stack<character> (), St.push (S.charat (0)), for (int i = 1; i< s.length (); i++) {if (! St.empty () && IsMatch (St.peek (), S.charat (i))//non-empty and the top of the stack matches the current character, pops up St.pop (); else {St.push (S.charat (i));}} if (St.empty ()) return True;return false; } Public Static boolean ismatch (char A,char b) {if ((a== ' (' &&b== ') ') | | (a== ' {' &&b== '} ') | | (a== ' [' &&b== ']) return true;else return false;}
Leetcode Valid parentheses Bracket matching problem