Topic
First, it is clear that there can be (()) ([]) such expressions.
Then it is easier to implement the algorithm using the stack.
Determines the total length, not a multiple of 2, returns false.
If the first one is)]}, returns false.
If yes ([{then pressed into the stack
If it is) then see if the top of the stack is (, if not, return false.) Other, similar.
Returns True if the stack is empty after the loop is executed. The stack is not empty and returns false.
Implement the stack with LinkedList.
constructors, for example:
LinkedList link=New LinkedList (); LinkedList<String> link=new linkedlist<string> ();
Note that it cannot be
linkedlist<char> link=new linkedlist<char> ();
This example is wrong. As to why it is wrong, I do not know. I have practiced, not, and see that there is no such usage on the Internet, all processing character char when it is treated as a string, such as the subject.
Method
Add method
Clear method
Clone method
Remove method
Get method
ImportJava.io.*;ImportJava.util.*; Public classsolution{ Public Static BooleanIsValid (String s) {intlen=s.length (); if(len%2==1) return false; Char[] c=S.tochararray (); inti; LinkedList<String> linkl=NewLinkedlist<string>(); intIndex=0; if(c[0]== ') ' | | c[0]== '] | | c[0]== '} ') return false; for(i=0;i<len;i++) { Switch(C[i]) { Case' (': Linkl.add ("); Break; Case‘)‘: if(Linkl.getlast () = = "(") Linkl.removelast (); Else return false; Break; Case' [': Linkl.add ("["); Break; Case‘]‘: if(Linkl.getlast () = = "[") Linkl.removelast (); Else return false; Break; Case' {': Linkl.add ("{"); Break; Case‘}‘: if(Linkl.getlast () = = "{") Linkl.removelast (); Else return false; Break; default:return false; } } if(Linkl.size () ==0) return true; Else return false; } Public Static voidMain (string[] args) {System.out.println (IsValid ("(([]))[]{}")); System.out.println (IsValid ("()[[{}")); System.out.println (IsValid ("(])[]{}")); System.out.println (IsValid ("(()])}[}[}[]][}}[}{})][[(]({])])}}(])){)((){")); }}
I love coding,coding make me happy.
I love remembering words, remembering words makes me happy.
Leetcode valid parentheses (easy)/java