面试常规算法题
一串字符串,先算括号里面的,然后再算外面的,与操作。。(主要考察括号处理,与操作没有实际意义)
import java.util.*;
public class Test {
public static void main(String[] args) {
String s = "0101(11001)11(101(110)111)111";
System.out.println(binary_and(s));
}
public static int binary_and(String s){
Stack<Character> stack = new Stack<>();
int count = 1, i = 0, kuohao = 0;
while(i < s.length()){
if(s.charAt(i) == '('){
kuohao ++;
stack.push(s.charAt(i));
i++;
while(kuohao != 0){
while(s.charAt(i) != ')'){
if(s.charAt(i) == '(') kuohao ++;
stack.push(s.charAt(i));
i++;
}
//i此刻等于右括号
int temp = 1;
while(stack.peek() != '('){
temp &= (stack.pop() - '0') ;
}
stack.pop(); // 把左括号弹出去
kuohao --;
stack.push((char)temp);
i++;
}
}else{
if(!stack.isEmpty()) count &= stack.pop() - '0';
count &= (s.charAt(i) - '0');
i++;
}
}
return count;
}
}
上一个版本有问题。。。自己写的算法怎么这么长,经常就陷入处理细节方面,而不是从宏观上去解决问题,导致细节特别多,代码越写越长,反而产生问题
import java.util.*;
public class Test {
public static void main(String[] args) {
String s = "1(01(11011)110)(0)";
System.out.println(binary_and(s));
}
public static int binary_and(String s){
Stack<Character> stack = new Stack<>();
int count = 1, i = 0, kuohao = 0;
while(i < s.length()){
if(s.charAt(i) == '('){
kuohao ++;
stack.push(s.charAt(i));
i++;
while(kuohao != 0){
while(s.charAt(i) != ')'){
if(s.charAt(i) == '(') kuohao ++;
stack.push(s.charAt(i));
i++;
}
//i此刻等于右括号
int temp = 1;
while(stack.peek() != '('){
temp &= (stack.pop() - '0') ;
}
stack.pop(); // 把左括号弹出去
kuohao --;
stack.push((char)temp);
i++;
}
}
if(!stack.isEmpty()){
count &= stack.pop() - '0';
continue;
}else{
count &= (s.charAt(i) - '0');
i++;
}
}
return count;
}
}
查看16道真题和解析