每日算法(二十二)-java判断字符串内容是否符合某种条件
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
这里想到用栈,先将字符转化为char数组,然后依次放入栈,当出现对应的反括号时,看堆顶是否与之配对,配对则取出,最后为空则返回true 代码如下
public static void result(String s){
Stack<Character> stack=new Stack<>();
char[] ch=s.toCharArray();
for(int i=0;i<ch.length;i++){
switch(ch[i]) {
case '{':
stack.push(ch[i]);
break;
case '[':
stack.push(ch[i]);
break;
case '(':
stack.push(ch[i]);
break;
case '}':
if(stack.peek()=='{'){
stack.pop();
break;
}
case ']':
if(stack.peek()=='['){
stack.pop();
break;
}
case ')':
if(stack.peek()=='('){
stack.pop();
break;
}
}
}
if(stack.isEmpty()){
System.out.println("true");
}else{
System.out.println("false");
}
}