public class Solution { Stack<char> S = new Stack<char>(); public bool IsValid(string s) { foreach (var c in s) { if (c == '(' || c == '[' || c == '{') { S.Push(c); } else if(c == ')') { if (S.Count > 0) { var k = S.Peek(); if (k == '(') { S.Pop(); } else { return false; } } else { return false; } } else if (c == ']') { if (S.Count > 0) { var k = S.Peek(); if (k == '[') { S.Pop(); } else { return false; } } else { return false; } } else if (c == '}') { if (S.Count > 0) { var k = S.Peek(); if (k == '{') { S.Pop(); } else { return false; } } else { return false; } } } if (S.Count > 0) { return false; } else { return true; } } }
https://leetcode.com/problems/valid-parentheses/#/description
补充一个python的实现:
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 n = len(s) 4 if n == 0: 5 return True 6 stack = [] 7 for c in s: 8 if c == '(' or c == '{' or c == '[': 9 stack.append(c) 10 elif c == ')': 11 if len(stack) > 0: 12 if stack[-1] == '(': 13 stack.pop(-1) 14 else: 15 stack.append(')') 16 else: 17 return False 18 elif c == '}': 19 if len(stack) > 0: 20 if stack[-1] == '{': 21 stack.pop(-1) 22 else: 23 stack.append('}') 24 else: 25 return False 26 elif c == ']': 27 if len(stack) > 0: 28 if stack[-1] == '[': 29 stack.pop(-1) 30 else: 31 stack.append(']') 32 else: 33 return False 34 if len(stack) == 0: 35 return True 36 else: 37 return False