zoukankan      html  css  js  c++  java
  • 刷题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,无需改进。

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    04-struts2框架中获取servlet api及Result结果类型
    03-Action类的创建方式及访问
    一位资深程序员大牛给予Java初学者的学习建议(转)
    C++中数组指针
    Ubuntu 开机出现 grub rescue> 终端模式修复方法
    windows和linux双系统下扩容方法
    C 字符串处理
    C++类中变量定义初始化总结
    python创建xml
    OpenBlas compile centOS6.7 ./kernel/x86_64/dgemm_kernel_4x4_haswell.S:2548: Error: no such instruction: `vpermpd $
  • 原文地址:https://www.cnblogs.com/siweihz/p/12234287.html
Copyright © 2011-2022 走看看