题解:
class Solution {
public boolean isValid(String s){
if (s == null || s.length() == 0) return true;
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Deque<Character> deque = new ArrayDeque<>();
for (char c : s.toCharArray()){
if (c == '(' || c == '[' || c == '{') {
deque.push(c);
}else {
if (deque.size() == 0 || map.get(c) != deque.pop()) return false;
}
}
return deque.size() == 0;
}
}
Java toCharArray() 方法:将字符串转换为字符数组
public class Test {
public static void main(String args[]) {
String Str = new String("www.runoob.com");
System.out.print("返回值 :" );
System.out.println( Str.toCharArray() );
}
}
输出为:返回值 :www.runoob.com
数组遍历方法:
for(type element: array)
{
System.out.println(element);
}
java map使用
- 初始化一个hashmap,其中<integer,integer>代表键和值的类型均为整型,若为字符型,则写<Character, Character>
Map<Character, Character> map = new HashMap<>();
-
使用map.containsKey()来查找map中是否包含某个键值
-
使用map.get()来获取某个键值对应的value
java deque使用
deque.push();
dedue.pop();
deque.size();