阿里筆試題(2018.3)


兩個相等長度字符串都由數字組成,每次只能進行交換操作或加一操作或減一操作,求出使兩個字符串相等的最少操作數。

思路:

  1.兩兩判斷交換之后操作少,還是不交換操作少。(不交換操作數為:對應數字差值的絕對值之和,交換的操作數為:交換之后對應數字差值的絕對值之和+1)

       2.如果交換可以減少操作數,把交換后的操作數與其它交換后的操作數比較,找到最小值,進行交換

       3.繼續1步驟,直到不能交換為止

    4.算出交換操作和加減操作之和 打印

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		String arr[]=bf.readLine().split(" ");
		int length=arr[0].length();
		int []number1=new int[length];
		int []number2=new int[length];
		for(int i=0;i<length;i++){
			number1[i]=Integer.parseInt(arr[0].substring(i,i+1));
			number2[i]=Integer.parseInt(arr[1].substring(i,i+1));
		}
		boolean flag;
		int count=0;
		while(true){
			flag=false;
			int a=-1;
			int b=-1;
			
			int min=Integer.MAX_VALUE;
			for(int i=0;i<length;i++){
				for(int j=0;j<length;j++){
					int temp1=Math.abs(number1[i]-number2[i]);
					int temp2=Math.abs(number1[j]-number2[j]);
					int temp3=Math.abs(number1[i]-number2[j]);
					int temp4=Math.abs(number1[j]-number2[i]);
					if(temp1+temp2>temp3+temp4+1){
						if(min>temp3+temp4+1){
							min=temp3+temp4+1;
							a=i;
							b=j;
							flag=true;
						}
					}
				}
			}
			if(flag==true){
				int temp=number1[a];
				number1[a]=number1[b];
				number1[b]=temp;
				count++;
			}else{
				break;
			}
		}
		for(int i=0;i<length;i++){
			count +=Math.abs(number1[i]-number2[i]);
		}
		System.out.println(count);
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM