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

【leetcode】Valid Parentheses

时间:2015-09-16 00:49:14      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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.

【My Solution:】

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    bool checkMatch(char first,char second){
        bool isMatch = false;
        if((first == ( && second == ))
            || (first == [ && second == ])
            || (first == { && second == }))
        {
            isMatch = true;
        }
        return isMatch;
    }

    bool isValid(string s) {
        bool isValid = false;
        vector<char> vTemp;
        if(s.length() <= 0){
            return isValid;
        }
        //vTemp.push_back(s[0]);
        for(int i = 0; i < s.length(); i++){
            if(vTemp.size() == 0){
                vTemp.push_back(s[i]);
            }else{
                vector<char>::iterator id = vTemp.end()-1;
                if(checkMatch((*id),s[i])){
                    vTemp.erase(id);
                }else{
                    vTemp.push_back(s[i]);
                }
            }
        }
        if(vTemp.size() == 0){
            isValid = true;
        }
        return isValid;
    }
};

int main(){
    Solution solution;
    solution.isValid("()");
    solution.isValid("()[]{}");
    solution.isValid("([)]");
    return 0;
}

【other‘s】算法使用相同,都使用栈来实现,但his更简洁,1、直接用到了已有的数据结构stack;2、匹配用到了ASCII码,但这样不合适,万一输入为“sdsf”等字符,则结果不正确。

public class Solution {
public boolean isValid(String s) {
    char [] arr = s.toCharArray();
    Stack stack = new Stack();
    for(char ch : arr){
        if(stack.isEmpty()){
            stack.push(ch);
        }else{
            char top = (char)stack.lastElement();
            if(ch - top == 1 || ch - top == 2){
                stack.pop();
            }else{
                stack.push(ch);
            }
        }
    }
    if(stack.isEmpty()){
        return true;
    }
    return false;
}

 

【leetcode】Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/xingyi7/p/4811847.html

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