题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
思路:
我们只需要将字符串依次取出一位,如果是开括号,放入栈中,如果是闭括号,从栈中弹出一位,看看是不是匹配.
代码:
import org.junit.Test;
import java.util.HashMap;
import java.util.Stack;
public class Leetcode4 {
HashMap<Character,Character> map = new HashMap<>();
Stack<Character> stack = new Stack<>();
private boolean isVilid(String x){
map.put(')','(');
map.put('}','{');
map.put(']','[');
for (int i = 0; i < x.length(); i++) {
char c = x.charAt(i);
if (map.containsKey(c)){
if (stack.isEmpty()){
return false;
}
char h = stack.pop();
if (h!=map.get(c)){
return false;
}
}else {
stack.push(c);
}
}
return stack.isEmpty();
}
@Test
public void test(){
System.out.println(isVilid("[]({}))"));
}
}
考察点:
stack和map的灵活运用
网友评论