【栈】【字符】Leetcode 20 有效的括号
- 解法1 栈的操作(先进后出)
---------------🎈🎈题目链接🎈🎈-------------------
解法1 栈的操作(先进后出)
新建栈:Stack<Character> mystack = new Stack<>();
遍历字符串:for(int i = 0; i < s.length() ; i++){char ch = s.charAt(i)}
判断栈是否为空:mystack.isEmpty()
向栈内加入元素(栈顶):mystack.push()
从栈内移除元素(栈顶):mystack.pop()
获取栈顶元素:mystack.peek()
时间复杂度O(N)
空间复杂度O(N)
class Solution {public boolean isValid(String s) {if(s.length() == 0) return true;Stack<Character> mystack = new Stack<>();for(int i = 0; i < s.length(); i++){char ch = s.charAt(i);if(mystack.isEmpty()){mystack.push(ch);continue;}else if((mystack.peek()=='(' && ch==')') || (mystack.peek()=='[' && ch==']') || (mystack.peek()=='{' && ch=='}')){mystack.pop();continue;}else{mystack.push(ch);}}if(mystack.isEmpty()) return true;else return false;}
}