刷题20. Valid Parentheses

一、题目说明

这个题目是20. Valid Parentheses,简单来说就是括号匹配。在学数据结构的时候,用栈可以解决。题目难度是Medium。

二、我的解答

栈涉及的内容不多,push、pop、top,。

我总共提交了3次:

第1次:Runtime Error,错误原因在于pop的时候,未判断栈是否为空。

第2次:Wrong Answer,这个是“眼大”疏忽导致的,我写的时候只考虑了()[]未考虑{}

第3次:终于正确了,性能还可以:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
Memory Usage: 8.5 MB, less than 73.64% of C++ online submissions for Valid Parentheses.

代码如下:

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

class Solution{
	public:
		bool isValid(string s){
			stack<char> st;
			char ch,curr;
			for(int i=0;i<s.size();i++){
				curr = s[i];
				if(curr=='(' || curr=='[' || curr=='{'){
					st.push(curr);
				}else if(curr==')'){
					if(st.empty()) return false;
					ch = st.top();
					if(ch != '('){
						return false;
					}
					st.pop();
				}else if(curr==']'){
					if(st.empty()) return false;
					ch = st.top();
					if(ch != '['){
						return false;
					}
					st.pop();
				}else if(curr=='}'){
					if(st.empty()) return false;
					ch = st.top();
					if(ch != '{'){
						return false;
					}
					st.pop();
				}
			}
			if(st.empty()) return true;
			else return false;
		} 
};
int main(){
	Solution s;
	
//	cout<<(true==s.isValid("()"))<<endl;
//	cout<<(true==s.isValid("()[]{}"))<<endl;
//	cout<<(false==s.isValid("(]"))<<endl;
//	cout<<(false==s.isValid("([)]"))<<endl;
//	cout<<(true==s.isValid("{[]}"))<<endl;
//	cout<<(false==s.isValid("]"))<<endl;
	cout<<(false==s.isValid("{[}]"))<<endl;
	return 0;
}

三、改进措施

这个题目相对来说简单,wonderful,无需改进。

所有文章,坚持原创。如有转载,敬请标注出处。
原文地址:https://www.cnblogs.com/siweihz/p/12234287.html