题目
输入只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ , ‘]’的字符串,判断字符串是否合法,”()” and “()[]{}”是合法的,”(]” and “([)]”是非合法的
分析
显然是使用栈进行实现
C++代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { public: bool isValid(string s) { stack<char> tmp; tmp.push('0'); for(int i = 0; i < s.size(); i ++) { if(abs(tmp.top() - s[i]) < 5 && tmp.top() != s[i]) tmp.pop(); else tmp.push(s[i]); } return tmp.size() == 1; } }; */ class Solution { public: bool (string s) { stack<char> tmp; for(int i = 0; i < s.size(); i ++) { if(s[i] == '[' || s[i] == '(' || s[i] == '{') tmp.push(s[i]); else{ if(tmp.empty()) return false; else{ if(abs(tmp.top() - s[i]) < 5) tmp.pop(); else return false; } } } if(tmp.empty()) return true; else return false; } };
|
Python代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Solution(object): def (self, s): """ :type s: str :rtype: bool """ stack = ['0'] for i in s: if i!=stack[-1] and abs(ord(i)-ord(stack[-1]))<5: stack.pop() else: stack.append(i) return stack==['0']
|
近期评论