20. Valid Parentheses

来源:互联网 发布:风之利刃数据 编辑:程序博客网 时间:2024/06/14 22:37

20. Valid Parentheses           

Given a string containing just the characters '(',')','{','}','[' and']', determine if the input string is valid.

The brackets must close in the correct order, "()" and"()[]{}" are all valid but"(]" and"([)]" are not.


       题目是一道简单题,就是确定三种括号的匹配关系是否合法,因为最内层的括号肯定是两两匹配的,所以首先想到用stack来做,难度较小吧。

       

class Solution {public:bool isValid(string s) {int i = s.size();//if (i % 2) return 0;stack<char> m;for (int j = 0; j < i; j++) {if (s[j] == ')' || s[j] == ']' || s[j] == '}') {if ((!m.empty()) && (m.top() == s[j]-1|| m.top() == s[j] - 2)) m.pop();else return 0;}else m.push(s[j]);}return m.empty() ? 1 : 0;}};
        代码写的可能不是很简洁,但是就是这么个想法。

  

1 0