Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
Given a string containing just the characters , determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
翻譯:
給定一個字符串,只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和’]’這些字符,檢查它是否是“有效”的。
括號必須以正確的順序關閉,例如”()” 和”()[]{}”都是有效的,”(]” 和”([)]”是無效的。
分析:
本題考查的是棧結構,具有后進先出的特性。有效包含2個方面,第一個是如果是關閉的括號,前一位一定要剛好有一個開啟的括號;第二個是最終結果,需要把所有開啟的括號都抵消完。一個比較容易出錯的地方是,遇到關閉括號時,要先判斷棧是否已經空了。
Java版代碼:
public class Solution {public boolean isValid(String s) {char[] charArr=s.toCharArray();List<Character> list=new ArrayList<>();for(Character c:charArr){if(c=='('||c=='{'||c=='['){list.add(c);}else{if(list.size()==0){return false;}char last=list.get(list.size()-1);if(c==')'&&last!='('){return false;}else if(c=='}'&&last!='{'){return false;}else if(c==']'&&last!='['){return false;}list.remove(list.size()-1);}}if(list.size()!=0){return false;}return true;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode刷题指南(一)
- 下一篇: Leet Code OJ 125. Va