leetcode20-valid parenthese
来源:互联网 发布:网页三剑客过时了 知乎 编辑:程序博客网 时间:2024/06/06 03:49
题目: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。
思路:本题是括号匹配问题,用栈就可以实现。只要找出不匹配的所有情况,分别处理即可。我们会发现共有三种情况:
- 对口形状不对:(]、([)]
- 括号右多:())
- 括号左多:(()
栈和单链表很像,采用头插法建立单链表其实就是在建栈。出栈pop(),进栈push()、读取栈顶元素peek()都是对头结点后的第一个节点进行操作。
测试通过代码:Your runtime beats 54.59% of javasubmissions
public class Solution{ char data; Solution next; public Solution (){ this.next=null; this.data=0; } boolean empty(Solution s){ if(s.next==null) return true; else return false; } //创建栈,代码没有用到 /* void creatStacklist(Solution s, String str){ for(int i=0;i<str.length();i++){ Solution lnode=new Solution(); lnode.data=str.charAt(i); lnode.next=s.next; s.next=lnode; } Solution p=s.next; while(p!=null){ System.out.println(p.data); p=p.next; } } */ //进栈操作 void push(Solution s, char data){ Solution lnode =new Solution (); lnode.data=data; lnode.next=s.next; s.next=lnode; } //出栈操作 boolean pop(Solution s){ if(s.empty(s)) return false; else { Solution p=new Solution (); p=s.next; s.next=p.next; return true; } } //读取栈顶元素 char peek(Solution s){ char x = 0; if(s.empty(s)) System.out.println("stack empty"); else{ x=s.next.data; } return x; } //主函数 public boolean isValid(String str) { Solution s=new Solution(); char[]a=str.toCharArray(); s.push(s,a[0]); for(int i=1;i<a.length;i++){ if(a[i]=='('||a[i]=='['||a[i]=='{') s.push(s, a[i]); else{ if(s.empty(s)) return false; else{ char tmp=s.peek(s); if((tmp=='('&&a[i]==')')||(tmp=='['&&a[i]==']')||(tmp=='{'&&a[i]=='}')){ s.pop(s); } else{ return false; } } } } if(s.empty(s)){ return true; } else { return false; } }}
0 0
- leetcode20-valid parenthese
- Valid Parenthese
- valid Parenthese
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- Leetcode20. Valid Parentheses
- leetcode20:Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 【LeetCode20】【Valid Parentheses】
- C++第4次作业
- Unity学习笔记七 - Survival Shooter Tutorial
- Android 系统相册不可见问题
- windows 卷管理API
- java学习之二:构造方法
- leetcode20-valid parenthese
- Unity AssetBundle打包与资源更新
- C++类实现公有继承
- UVA11548 DP计算添加多少元素可以构成回文字符串
- Java技术核心卷I学习笔记——基本的程序设计结构
- 安卓首选项preference的用法
- 可移植C
- hdu Summer Holiday(tarjan)
- BZOJ-2038-[2009国家集训队]小Z的袜子(hose)(莫队)