[Leetcode]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来保存左边括号,遇到右边括号就和栈顶元素去匹配,匹配成功继续往后走,匹配失败迭代结束。

当整个字符串都遍历完成之后,要检查stack是否为空,如果不为空证明左侧括号数量多了,返回FALSE。

class Solution {
public:
	bool isValid(string s) {
		int len = s.length();
		if (0 == len) return true;
		stack<char> v;
		for (int i = 0; i < len; i++){
			if (isLeft(s[i])) v.push(s[i]);
			else{
				if (v.empty()) return false;
				else{
					if (isCouple(v.top(), s[i])){
						v.pop();
					}
					else{
						return false;
					}
				}
			}
		}
		if(v.empty())
		    return true;
		else
		    return false;
		
	}
	bool isCouple(char a,char b){<span style="white-space:pre">					</span>//检查是否匹配
		switch (a){
		case '(':
			if (b == ')') return true;
			else return false;
			break;
		case '[':
			if (b == ']') return true;
			else return false;
			break;
		case '{':
			if (b == '}') return true;
			else return false;
			break;
		}
	}
	bool isLeft(char a){  <span style="white-space:pre">						</span>//确定括号方向
		if (a == '(' || a == '{' || a == '['){
			return true;
		}
		else{
			return false;
		}
	}
};

递归算法:

class Solution {
public:
	bool isValid(string s) {
		int len = s.length();
		if (0 == len) return true;
        if(len%2) return false;
		for (int i = 0; i < len; i++){
			 if(isCouple(s[i-1], s[i])  
            {  
                string ss = s.substr(0, i-1) + s.substr(i+1);  
                return isValid(ss);  
            }  
		}
		return false;
	}
	bool isCouple(char a,char b){
		switch (a){
		case '(':
			if (b == ')') return true;
			else return false;
			break;
		case '[':
			if (b == ']') return true;
			else return false;
			break;
		case '{':
			if (b == '}') return true;
			else return false;
			break;
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值