1. 程式人生 > 實用技巧 >Leecode no.20 合理的括號

Leecode no.20 合理的括號

package com.example.demo.leecode;

import java.util.Stack;

/**
* 合理的括號
* @Date 2020/12/10
* @author Tang
*
* 給定一個只包括 '(',')','{','}','[',']' 的字串,判斷字串是否有效。
* 有效字串需滿足:
* 左括號必須用相同型別的右括號閉合。
* 左括號必須以正確的順序閉合。
* 注意空字串可被認為是有效字串。
*/
public class ValidParentheses {

private Stack<Character> stack = new Stack();

public boolean execute(String s){

if(s == null || "".equals(s.trim())){
return false;
}

char[] chars = s.toCharArray();

for(char c : chars){
if(ifMatching(c)){
stack.pop();
continue;
}
stack.push(c);
}

return stack.size() == 0;
}

/**
* 是否匹配上棧中上一個字元
* @param c
* @return
*/
private boolean ifMatching(char c){
if(stack.size() == 0){
return false;
}

switch (stack.peek()){
case '{':
return c == '}';
case '(':
return c == ')';
case '[':
return c == ']';
default:
return false;
}


}


public static void main(String[] args) {

String value = "{(]}";
boolean result = new ValidParentheses().execute(value);
System.out.println(result);
}


}