2020滴滴算法笔试第一题:
2020滴滴算法笔试第一题:
如有错误请都多指出~暂测都可以
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/*
* 一个运算式,不改变运算符的位置,将运算式中的数字进行排序,不改变原结果
第一行数字是运算式中数字的个数
第二行是运算式,各符号之间以空格间隔
如:
6
3 + 2 + 1 - -4 * -5 + 1
输出应该是
1 + 2 + 3 - -5 * -4 + 1
*/
/*
* 连加、连减、连乘、连除
*/
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String line = scanner.nextLine();
String[] input = line.split(" ");
ArrayList<Integer> nums = new ArrayList<Integer>();
StringBuilder f = new StringBuilder();
f.append("+");
// char[] result = new char[n+n-1];
for(int i = 0;i<input.length;i++) {
if(i%2!=0) {
f.append(input[i]); //存储符号
}else {
nums.add(Integer.parseInt(input[i])); //存储所有的符号和数字
}
}
String fu = f.toString();
int l = 0, r = 0;//定义两个指针,确定需要排序的区间
int index = 0;
while(index<f.length()) {
if(fu.charAt(index)=='+') {
l = index;
index+=1;
while((index< n-1) && fu.charAt(index)=='+') {
index+=1;
}
if(index==n-1 || (index<n-1 && fu.charAt(index)=='-') ){
r = index; //不包含r 位置的元素
}else {
r = index-1;
}
Collections.sort(nums.subList(l, r));
}else if(fu.charAt(index)=='-') {
l = index;
index+=1;
while((index< n-1) && fu.charAt(index)=='-') {
index+=1;
}
if(index==n-1 || (index<n-1 && fu.charAt(index)=='+') ) {
r = index; //不包含r 位置的元素
}else {
r = index-1;
}
Collections.sort(nums.subList(l, r));
}else if(fu.charAt(index)=='*') {
l = index-1;
index+=1;
while((index< n-1) && fu.charAt(index)=='*') {
index+=1;
}
r = index; //不包含r 位置的元素
Collections.sort(nums.subList(l, r));
}else if(fu.charAt(index)=='/') {
l = index-1;
index+=1;
while((index< n-1) && fu.charAt(index)=='/') {
index+=1;
}
r = index; //不包含r 位置的元素
Collections.sort(nums.subList(l, r));
}
}
StringBuilder out = new StringBuilder();
out.append(nums.get(0));
for(int i = 1;i < nums.size();i++) {
out.append(" ").append(fu.charAt(i)).append(" ").append(nums.get(i));
}
System.out.println(out.toString().trim());
}
}

