給定一個只包含(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和‘]’的字符串,驗證它是不是有效的。括號必須配對,而且要以正確的順序。html
用一個棧來對輸入的括號串進行處理,若是是左括號就入棧,若是是右括號就與棧頂元素看是否組成一對括號,組成就彈出,而且處理下一個輸入的括號,若是不匹配就直接返回結果。java
import java.util.*; public class Solution { public boolean isValid(String s) { Deque<Character> stack = new LinkedList<>(); int index = 0; Character top; while (index < s.length()) { Character c = s.charAt(index); switch (c) { case '(': case '[': case '{': stack.addFirst(c); break; case ')': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '(') { stack.removeFirst(); } else if (top == '[' || top == '{') { return false; } else { stack.addFirst(c); } break; case ']': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '[') { stack.removeFirst(); } else if (top == '(' || top == '{') { return false; } else { stack.addFirst(c); } break; case '}': if (stack.isEmpty()) { return false; } top = stack.getFirst(); if (top == '{') { stack.removeFirst(); } else if (top == '[' || top == '(') { return false; } else { stack.addFirst(c); } break; default: return false; } index++; } return stack.isEmpty(); } }
原本想找找現成的,去,都寫的好複雜。本身寫一個吧。挺有成就感。哈哈spa
|