Skip to content

Commit f1cb5c3

Browse files
author
Li Li
committed
add code of 20
1 parent 99a4872 commit f1cb5c3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// condense and smart one, not a direct thought
2+
public class Solution {
3+
public bool IsValid(string s) {
4+
if (s == null || s.Length == 0) return false;
5+
if (s.Length % 2 == 1) return false;
6+
Stack<char> stack = new Stack<char>();
7+
foreach (char c in s) {
8+
if (c == '(') stack.Push(')');
9+
else if (c == '[') stack.Push(']');
10+
else if (c == '{') stack.Push('}');
11+
else if (stack.Count == 0 || stack.Pop() != c) return false;
12+
}
13+
return stack.Count == 0;
14+
}
15+
}
16+
17+
// direct thought solution
18+
public class Solution {
19+
public bool IsValid(string s) {
20+
if (s == null || s.Length == 0) return false;
21+
if (s.Length % 2 == 1) return false;
22+
Stack<char> stack = new Stack<char>();
23+
foreach (char c in s) {
24+
if (c == '(' || c == '[' || c == '{') stack.Push(c);
25+
else if (stack.Count == 0) return false;
26+
else if (c == ')' && stack.Peek() == '(') stack.Pop();
27+
else if (c == ']' && stack.Peek() == '[') stack.Pop();
28+
else if (c == '}' && stack.Peek() == '{') stack.Pop();
29+
else return false;
30+
}
31+
return stack.Count == 0;
32+
}
33+
}

0 commit comments

Comments
 (0)