LeetCode之Valid Parentheses
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Valid Parentheses
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、題目
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.
?
2、思路
用stack來實現,左邊的進棧,如果是右邊的出棧,發現沒有或者不匹配就返回false
3、代碼實現
public class Solution {public boolean isValid(String s) {if (s == null || s.length() == 0) {return false;}char chars[] = s.toCharArray();Stack<Character> stack = new Stack<Character>();for (int i = 0; i < chars.length; ++i) {if (chars[i] == '(' || chars[i] == '{' || chars[i] == '[') {stack.add(chars[i]);} else {if (!stack.isEmpty()) {Character value = stack.pop();if (chars[i] == ')') {if (value != '(') return false;}if (chars[i] == '}') {if (value != '{') return false;}if (chars[i] == ']') {if (value != '[') return false;}} else {return false;}}}return stack.isEmpty();} }?
?
總結
以上是生活随笔為你收集整理的LeetCode之Valid Parentheses的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux之用openssl命令Base
- 下一篇: LeetCode之Remove Elem