【leetcode】Valid Parentheses
2015-09-15 23:19
260 查看
Given a string containing just the characters
The brackets must close in the correct order,
【My Solution:】
【other's】算法使用相同,都使用栈来实现,但his更简洁,1、直接用到了已有的数据结构stack;2、匹配用到了ASCII码,但这样不合适,万一输入为“sdsf”等字符,则结果不正确。
'(',
')',
'{',
'}',
'['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; }
相关文章推荐
- jni中文字符串乱码的处理方法
- CodeForces 576A - Vasya and Petya's Game
- FP_growth算法
- 求List集合的并集、交集、差集
- Thinkphp 几个调试配置,常量设置项
- 关于JavaScript中的事件代理
- Nacl开发
- java线程中断和终止线程运行
- MyBatis学习手记(二)MyBatis缓存机制
- java学习记录之——泛型
- c++主函数输出圆柱体的半径和高,然后调用函数输出其体积
- 一千零一夜:检查数组包含某一目标元素的几种方法分析
- java序列化和反序列化
- 第一百六十六天 how can I 坚持
- scala初学笔记
- 9月10日 rpm和yum程序总结
- Docker 容器互联
- Apriori算法
- iOS经典讲解之复杂对象的数据持久化-归档与反归档
- 链表java_类c++,linkedlist,iterator