首页 > 其他 > 详细

leetcode------Plus One

时间:2015-01-18 12:56:32      阅读:192      评论:0      收藏:0      [点我收藏+]
标题: Valid Parentheses
通过率: 27.7%
难度: 简单

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.

本题是传统的符号匹配题用一个栈来模拟就行了。遇见(,{,[全部进栈,遇到),},]进行弹栈比较,如果不是() [] {}则返回错误,直接看代码:

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         int len=s.length();
 4         Stack<Character> stack = new Stack<Character>();  
 5         for(int i=0;i<len;i++){
 6             char tmp=s.charAt(i);
 7             if(tmp==‘(‘||tmp==‘{‘||tmp==‘[‘){
 8                 stack.push(tmp);
 9             }
10             if(tmp==‘)‘||tmp==‘}‘||tmp==‘]‘){
11                 if(stack.empty())return false;
12                 char ctr=stack.pop();
13                 if(tmp==‘)‘&&ctr==‘(‘) continue;
14                  if(tmp==‘]‘&&ctr==‘[‘) continue;
15                  if(tmp==‘}‘&&ctr==‘{‘) continue;
16                  else return false;
17             }
18         }
19         if(stack.empty())return true;
20         else{
21             return false;
22         }
23     }
24 }

 

leetcode------Plus One

原文:http://www.cnblogs.com/pkuYang/p/4231595.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!