zoukankan      html  css  js  c++  java
  • Leetcode[20]-Valid Parentheses

    Link: https://leetcode.com/problems/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.


    思路:借助vector容器,存放字符’(‘,’{‘,’[‘,从左到右的读取字符串的每个字符,

    • 假设字符为上面给定的三个。则增加到vector中;
    • 假设不是,在确保vector容器有字符的情况下,则让其和vector的最后一个比較;

      • 假设是匹配的。则将vector容器的大小缩减为size()-1;
      • 假设不匹配。则返回false;
    • 最后,假设vector元素所有匹配完了,则返回true,否则返回false;

    代码例如以下(c++):

    class Solution {
    public:
        bool isValid(string s) {
            vector<char> str;
            int len = s.length();
    
            for(int i=0; i<len; i++){
                if(isThose(s[i])) {
                    str.push_back(s[i]);
                    continue;
                }
                if(str.size()>0 && isTrue(str[str.size()-1],s[i])) {
                    cout<<str.size()<<"f"<<isTrue(str[str.size()-1],s[i])<<endl;
                    str.resize(str.size()-1);
                }else{
                    return false;
                }
            }
            if(str.size() == 0)
                return true;
            else
                return false;
        }
    
        bool isThose(char &a){
            if(a == '{' || a == '(' || a == '[')return true;
            return false;
        }
    
        bool isTrue(char &a, char &b){
            if( a == '(' && b == ')' ) return true;
            else if( a == '[' && b == ']' ) return true;
            else if( a == '{' && b == '}' ) return true;
    
            return false;
        }
    };
  • 相关阅读:
    课堂作业1
    懒人创造了方法
    四则运算
    动手动脑与原码反码补码
    java测试感受
    暑假进度报告四
    暑假进度报告三
    暑假进度报告二
    暑假进度报告一
    《大道至简》读后感
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7283543.html
Copyright © 2011-2022 走看看