Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
020.valid_parentheses (Easy)
links:
Title: https://oj.leetcode.com/problems/valid-parentheses/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Determines whether a parenthesis string is valid.
Analysis:
Directly with the stack simulation, very simple.
The parentheses matching in Java can be written with if, can also be used, and can be used HashMap<Character, Character>
"(){}[]".indexOf(s.substring(i, i + 1)
. (This discussion can also be used for C + + and Python)
Here C + + is used if match, Java with IndexOf, Python with Dict.
Code:
C++:
Class Solution {Public:bool IsValid (string s) {stack<char> Stk;int len = s.length (); for (int i = 0; i < len; i++) {if (s[i] = = ' (' | | s[i] = = ' [' | | s[i] = = ' {') {Stk.push (s[i]);} else {if (Stk.empty ()) return false;if (' stk.top () = = ' (' && S[i] = = ') Stk.pop (); else if (stk.top () = = ' [' && s[i] = = '] ') stk.pop (); else if (stk.top () = = ' {' &am p;& S[i] = = '} ') Stk.pop (); Elsereturn false;}} return Stk.empty ();}};
Java:
public class Solution {public Boolean isValid (String s) { stack<integer> Stk = new stack<integer> (); for (int i = 0; i < s.length (); ++i) { int pos = "() {}[]". IndexOf (S.substring (i, i + 1)); if (pos% 2 = = 1) { if (stk.isempty () | | Stk.pop ()! = pos-1) return false; } else { stk.push (POS); } } return Stk.isempty ();} }
Python:
Class solution: # @return A Boolean def isValid (self, s): MP = {') ': ' (', '] ': ' [', '} ': ' {'} STK = []
for ch in s: if ch in ' ([{': stk.append (CH) else: if not STK or mp[ch]! = Stk.pop (): return FALSE
return not STK
[Leetcode] 020. Valid parentheses (Easy) (C++/java/python)