標籤:leetcode java valid parentheses
題目:
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.
題意:
給定一個字串,包含以下字元‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and ‘]‘,判斷輸入的字串是否有效。
這些括弧必須按正確的順序關閉,"()" and "()[]{}"就是有效,"(]" and "([)]" 就是無效的。
演算法分析:
該題是匹配括弧是否匹配合法問題,可以採用棧來實現,而棧一般採用數組來進行標示。如果遇到字元(,{和[,則將其壓入棧中,如果遇到),}和],則需要對棧頂元素進行判定,看是否與括弧相匹配,如果匹配則彈出棧頂元素,否則則認為匹配不合法,直接結束匹配過程。
演算法流程如下:
定義數組棧stack;foreach c in String: if c 為(,{,[ then stack.push(c); if c 為 ), }, ] then 判定stack是否為空白和stack.top是否與c相匹配。
AC代碼:
public class Solution {private boolean a;private boolean flag;private int i;private int n;public boolean isValid(String s) { Stack st= new Stack(); // 建立堆棧對象 if (s.length()%2!=0) flag=false; else { i=0; st.push(s.charAt(0)); while (i<s.length()-1) { if(st.empty()) { st.push(s.charAt(i+1)); i++; } if((st.peek().toString().charAt(0)=='('&&s.charAt(i+1)==')')||(st.peek().toString().charAt(0)=='['&&s.charAt(i+1)==']' )||(st.peek().toString().charAt(0)=='{'&&s.charAt(i+1)=='}')) { st.pop(); } else st.push(s.charAt(i+1)); i++; } flag=st.empty(); } return flag; }}
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Valid Parentheses