题目:
题目描述: * 给出一个仅包含加减乘除四种运算符的算式(不含括号),如1+2*3/4,在保持运算符顺序不变的情况下
,现在你可以进行若干次如下操作: * 如果交换相邻的两个数,表达式值不变,那么你就可以交换这两个数。 * * 现在你可以
进行任意次操作,使得算式的数字序列字典序最小,然后输出结果,数字之间的字典序定义为若a<b则a的字典序小于b。
* 样例输入 * 6 * 3 + 2 + 1 + -4 * -5 + 1
案例结果是:
1 + 2 + 3 + -5 * -4 + 1
要求字典序最小 不是应该结果是这个吗
* 1 + 1 + 2 + -5 * -4 + 3
附上菜鸡代码(怎样接收输入的值啊 只能接收一个怎么回事)
public class Main1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// int n = scanner.nextInt();
//int n=0;
String in = scanner.nextLine();
String[] inStrs = in.split(" ");
int n = inStrs.length;
int opeLen = n >> 1;
final char[] operator = new char[opeLen];
int numsLen = (n+1) >> 1;
Integer[] nums = new Integer[numsLen];
for(int i=0;i<n;i++){
if((i&1)==0){
nums[i/2] = Integer.valueOf(inStrs[i]);
}else{
operator[(i)/2] = inStrs[i].charAt(0);
}
}
int result =cacu(operator,nums);
for(int i=0;i<numsLen;i++){
for(int j=i;j<numsLen;j++){
if(nums[j]<nums[i]){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
if(cacu(operator,nums) != result){
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}
//形成结果串
StringBuffer sb = new StringBuffer();
sb.append(nums[0]+" ");
for(int i=1;i < numsLen ;i++){
sb.append(operator[i-1]+" ");
sb.append(nums[i]+" ");
}
System.out.println(sb.toString());
}
public static int cacu(char[] operator,Integer[] nums){
Stack<Integer> numStack = new Stack<Integer>();
Stack<Character> operStack = new Stack<Character>();
numStack.push(nums[0]);
//计算乘除法
for(int i=1;i<nums.length;i++){
if(operator[i-1] == '*'){
Integer p = numStack.pop();
int res = p * nums[i];
numStack.push(res);
}else if(operator[i-1] == '/'){
Integer p = numStack.pop();
int res = p / nums[i];
numStack.push(res);
}else {
operStack.push(operator[i-1]);
numStack.push(nums[i]);
}
}
//计算加减法
while(!numStack.isEmpty()&&!operStack.isEmpty()){
Character ope = operStack.pop();
Integer n1 = numStack.pop();
Integer n2 = numStack.pop();
if(ope == '+'){
numStack.push(n2+n1);
}else if(ope == '-'){
numStack.push(n2-n1);
}
}
return numStack.pop();
}
}
输出结果:
#滴滴##笔试题目##秋招##题解#