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.
思路:
- 将‘{’和‘}’、‘[’和‘]’、’(‘和‘)’放入到HashMap中
- 遍历字符串s,将‘{’‘[’‘(’入栈,如果是‘]’或‘}’或‘)’从map中取出其对应的字符和栈顶元素比较,相等出栈,否则,返回false;
- 判断栈中的元素是否为空,为空返回true,否则,返回false;
细节问题:
- 如果case为“}”或者“](){}”,是不是应该单独在考虑下,首字符的问题。有两种做法:第1种做法:先判断首字符,不为‘(’、‘{’、‘[’,直接返回false;第2种做法:在遍历字符串s中,通过使用标记位进行判断。
测试的所有case:
println(s.isValid("()[]{}"));
println(s.isValid("()"));
println(s.isValid("()}"));
println(s.isValid("}()"));
println(s.isValid("([)]"));
println(s.isValid("}"));
println(s.isValid(""));
代码:
if (s == null || s.equals(""))
return true;
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
char ch = '0';
boolean isFirst = true;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if ('(' == ch || '{' == ch || '[' == ch) {
stack.push(ch);
isFirst = false;
} else {
// 处理“]”类型的case;
if (isFirst) {
return false;
}
if (!stack.empty() && stack.peek() == map.get(ch)) {
stack.pop();
} else {
return false;
}
}
}
if (stack.empty()) {
return true;
} else {
return false;
}
遇到问题:
编程的过程中,用到了Stack 对象 stack,stack.empty()和stack.isEmpty()两种方法的区别和联系,百度了下没有搜到?
- API是这样说的:
isEmpty()方法:—该方法是Vector类中的方法,Stack类继承了Vector
public boolean isEmpty()
测试此向量是否不包含组件。
指定者:
接口 Collection 中的 isEmpty
指定者:
接口 List 中的 isEmpty
覆盖:
类 AbstractCollection 中的 isEmpty
返回:
当且仅当此向量没有组件(也就是说其大小为零)时返回 true;否则返回 false。
empty()方法:
empty
public boolean empty()
测试堆栈是否为空。
返回:
当且仅当堆栈中不含任何项时返回 true;否则返回 false。
不知您是否看出来了什么???明白吗?