标签:tac ppi ack ISE 算法 public 空字符串 mapping i++
栈是Vector的一个子类,它实现了一个标准的后进先出的栈。
这是一道LeetCode的简单算法题。
给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判断字符串是否有效。
有效字符串需满足:
注意空字符串可被认为是有效字符串。
输入: "()[]{}"
输出: true
输入: "([)]" 输出: false
import java.util.HashMap;
import java.util.Stack;
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isValid("({})"));
}
private HashMap<Character, Character> mappings;
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(‘)‘, ‘(‘);
this.mappings.put(‘}‘, ‘{‘);
this.mappings.put(‘]‘, ‘[‘);
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (this.mappings.containsKey(c)) {
char topElement = stack.empty() ? ‘#‘ : stack.pop();
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}
标签:tac ppi ack ISE 算法 public 空字符串 mapping i++
原文地址:https://www.cnblogs.com/diehuacanmeng/p/13253277.html