leetcode20.ValidParentheses

来源:互联网 发布:php 实例化对象的本质 编辑:程序博客网 时间:2024/05/29 14:15
原题如下: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.

题目的意思是给定一个只包含上述几个字符的字符串,来判断字符串的顺序是否合法,这个题目在之前学习数据结构的时候,栈的时候学习过,其实就是匹配问题。题目中还有一种方式就是字符内部还有字符,那样也是合法的。

栈有很多很有意思的地方,这篇博客讲了一些关于栈和队列的一些操作。http://blog.csdn.net/zhy_cheng/article/details/8090346

这一篇博客详细写出栈的实现http://blog.csdn.net/xiaoding133/article/details/6897101

解题思路;首先我们定义一个栈,如果读取到的字符是左边的,则进行压栈操作,如果读取到的是右边的,先判断此时栈是不是空的,如果是空的,则匹配不成功,退出。如果不是空的,则将其与栈的顶部的元素进行匹配,如果匹配成功,则弹出栈顶元素,然后进行下一个字符的读取。如果不匹配,则结束,退出。当我们遍历完一遍元素时候,如果栈中的元素不为空,则说明还存在不匹配的元素,说明匹配失败。

代码如下:

#include<iostream>#include<string>#include<stack>using namespace std;bool isValid(string s){stack<char> charstack;int i = 0;while (i!=s.length()){char c = s[i];if (c!=')'&&c!='}'&&c!=']'){charstack.push(c);}else{if (charstack.size() == 0){return false;}char pre = charstack.top();switch (c){case ')':if (pre != '('){return false;}else{charstack.pop();break;}case ']':if (pre != '['){return false;}else{charstack.pop();break;}case '}':if (pre != '{'){return false;}else{charstack.pop();break;}}}i++;}if (charstack.size()==0){return true;}else{return false;}}


0 0