LeetCode: Valid Parentheses

一次过

 1 class Solution {

 2 public:

 3     bool isValid(string s) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         stack<char> S;

 7         for (int i = 0; i < s.size(); i++) {

 8             if (s[i] == '(' || s[i] == '[' || s[i] == '{') S.push(s[i]);

 9             else {

10                 if (S.empty()) return false;

11                 char tmp = S.top();

12                 if (s[i] == ')') {

13                     if (tmp == '(') S.pop();

14                     else return false;

15                 }

16                 if (s[i] == ']') {

17                     if (tmp == '[') S.pop();

18                     else return false;

19                 }

20                 if (s[i] == '}') {

21                     if (tmp == '{') S.pop();

22                     else return false;

23                 }

24             }

25         }

26         if (S.empty()) return true;

27         else return false;

28     }

29 };

 C#

 1 public class Solution {

 2     public bool IsValid(string s) {

 3         Stack<char> S = new Stack<char>();

 4         for (int i = 0; i < s.Length; i++) {

 5             if (s[i] == '(' || s[i] == '[' || s[i] == '{') S.Push(s[i]);

 6             else {

 7                 if (S.Count == 0) return false;

 8                 char peek = S.Peek();

 9                 if (s[i] == ')') {

10                     if (peek == '(') S.Pop();

11                     else return false;

12                 }

13                 if (s[i] == ']') {

14                     if (peek == '[') S.Pop();

15                     else return false;

16                 }

17                 if (s[i] == '}') {

18                     if (peek == '{') S.Pop();

19                     else return false;

20                 }

21             }

22         }

23         return S.Count == 0;

24     }

25 }
View Code

 

你可能感兴趣的:(LeetCode)