滴滴开发岗笔试第一题,一种可能的解(Java)

	
	
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class DiDi1 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		//(1)
		int n = Integer.parseInt(scan.nextLine());
		//(2)
		String strAll = scan.nextLine();
		String[] strArr = strAll.split(" ");
		scan.close();
		if(strArr.length != 2*n-1) {
			return;
		}
		
		String strResult = change(strArr);
		System.out.println(strResult);
	}
	
	/**
	 * 处理字符串数组
	 * @param arr 字符串数组
	 * @return 
	 */
	public static String change(String[] arr) {
		if(arr.length == 0) {
			return "";
		}
		if(arr.length == 1) {
			return arr[0];
		}
		// 定义起始位置、终止位置
		int from = 0;
		int to = 0;
		// 标定当前运算符
		String current = "";
		
		while(from != arr.length-1) {
			ArrayList<String> tempList = new ArrayList<String>();
			tempList.add(arr[from]);
			current = arr[from+1];
			// 当起始符号为 减号或者除号时,不能交换前后数字位置
			if(current.equals("-") || current.equals("/")) {
				from += 2;
				to = from;
				continue;
			}
			// 从当前起点from开始,先后找可以交换的部分
			for(int i=from; i<arr.length; i++) {
				if(i%2 == 0 && i>from) {
					// 若当前符号位置的数字后面一个符号与current符号一致,则此元素可以交换,并继续向后找
					if(arr[i+1].equals(current)) {
						tempList.add(arr[i]);
						to = i+2;
						continue;
					}else if(current.equals("*") || (current.equals("+") && arr[i+1].equals("-"))){  
						// 符号与current不同但current为*, 或者当前current为+且后一个符号为-,添加当前元素后,break
						tempList.add(arr[i]);
						to = i+2;
						break;
					}else {
						break;
					}
				}
			}
			// 将可交换的部分的数字进行排序
			Object [] arr1 = tempList.toArray();
			int[] arrInt = new int[arr1.length];
			for(int i=0;i<arr1.length; i++) {
				arrInt[i] = Integer.parseInt(arr1[i].toString()); 
			}
			Arrays.sort(arrInt);
			// 将排序后的内容更新到原数组中去
			for(int k=0; k<arrInt.length; k++) {
				arr[from+2*k] = arrInt[k]+"";
			}
			//
			from = to;
		}
		// 拼接字符串
		String result = "";
		for(int j=0; j<arr.length; j++) {
			result = result+" "+arr[j];
		}
		return result.trim();
	}

}


原题目给的测试用例
6
3 + 2 + 1 + -4 * -5 + 1
可以通过,不知道具体能够通过多少测试用例。
#滴滴##笔试题目#
全部评论

相关推荐

点赞 4 评论
分享
牛客网
牛客企业服务