码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

时间:2015-06-06 09:18:14      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:算法   c++   

为了在运行中避免可能出现的危险,即当string emuStack为空,emuStack.begin()和emuStack.end()是什么。采取的策略是先将emuStack重置为非空,再进行其他操作,这样就永远不可能碰到底部。

#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
    bool isValid(string s) {    
		
		if(s.size() == 0)
			return true;

		string emuStack = "s";
		string::iterator iter1 = s.begin();
		string::iterator iter2 = emuStack.begin();
		for(; iter1 != s.end(); iter1++) {
				if(*iter1 == '}') {
					if(*iter2 == '{') {
						emuStack.erase(iter2);
						iter2 = emuStack.end() - 1;
						continue;
					}
				}

				if(*iter1 == ']') {
					if(*iter2 == '[') {
						emuStack.erase(iter2);
						iter2 = emuStack.end() - 1;
						continue;
					}
				}

				if(*iter1 == ')') {
					if(*iter2 == '(') {
						emuStack.erase(iter2);
						iter2 = emuStack.end() - 1;
						continue;
					}
				}

				if((*iter1 == '{') || (*iter1 == '}') || (*iter1 == '[') || (*iter1 == ']') || (*iter1 == '(') || (*iter1 == ')')) {
					emuStack += *iter1;
					iter2 = emuStack.end() - 1;
				}
		}

		//cout << emuStack << endl;

		if(emuStack.size() == 1)
			//cout << "valid" << endl;
			return true;
		else
			//cout << "no valid" << endl;
			return false;

		//getchar();

		//return 1;
	}
};

int main() {
	//string s = "a{b[c(d)e]f}g";
	string s = "]";
	Solution solution;
	cout << solution.isValid(s) << endl;

	getchar();
	
	return 1;
}

Valid Parentheses

标签:算法   c++   

原文地址:http://blog.csdn.net/guanzhongshan/article/details/46381863

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!