4.栈
栈(stack)
栈是一种特殊的线性表,只能在一端进行操作(后进先出,Last In First Out,LIFO)
- 往栈中添加元素的操作,一般叫做push,入栈
- 从栈中移除元素的操作,一般叫做pop,出栈(只能移除栈顶元素,也叫做弹出栈顶元素)
注意,这里说的栈与内存中的栈空间是两个不同的概念
判断字符串里面的括号是否是成对出现
python实现
SYMBOLS = {'}': '{', ']': '[', ')': '(', '>': '<'} SYMBOLS_L, SYMBOLS_R = SYMBOLS.values(), SYMBOLS.keys() def check(s): stack = [] for c in s: if c in SYMBOLS_L: # 左符号入栈 stack.append(c) elif c in SYMBOLS_R: # 右符号要么出栈,要么匹配失败 if stack and stack[-1] == SYMBOLS[c]: stack.pop() else: return False return True print(check("3 * {3 +[(2 -3) * (4+5)]}")) print(check("3 * {3+ [4 - 6}]"))
java实现
package zh.datastructures.stack; import java.util.Stack; public class Parentheses { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c=='(' || c=='{' ||c== '[') { stack.push(c); }else { if (stack.isEmpty()) return false; char left = stack.pop(); if (left == '(' && c != ')') return false; if (left == '[' && c != ']') return false; if (left == '{' && c != '}') return false; } } return stack.isEmpty(); } public static void main(String[] args) { Parentheses test = new Parentheses(); System.out.println(test.isValid("{}("));//false System.out.println(test.isValid("{}"));//true } }