01序列交換次數

問題描述:

給定一個01序列串,現在需要將這個字符串改爲“非遞減“有序序列,請問其最小交換次數(任意兩個位置可互換)?

Input

輸入數據第一行是一個正整數T(T<100),表示有T組測試數據;

接下來輸入T行,每行一個01串。


50%的字符串長度在【1,100】;

95%的字符串長度在【1,10000】;

100%的字符串長度在【1,1000000】;

Output

對於每組測試數據,請輸出排成“非遞減有序序列”的最小交換次數。

每組輸出佔一行。

import java.util.Scanner;
import java.util.Vector;

public class counts01 {
	//計算01序列變爲”非遞減序列“情況的最小交換序列
	//設置雙指針,begin,end,str[end]=0,str[begin]=1,表示需要交換;str[end]=1,end前移;str[begin]=0(隱含str[end]=0),指針begin後移。
	public void getMinExchange01Method1() {
		
		Scanner scanner = new Scanner(System.in);
		//記錄有多少組數據
		int dataLength = scanner.nextInt();
		//在讀取數據長度之後,scanner並沒有切換到下一行
		scanner.nextLine();
		//保存每個字符串的交換次數
		Vector<Integer> result = new Vector<>();
		
		for(int i=0;i<dataLength;i++){
			String str = scanner.nextLine();
			int begin = 0;
			int end = str.length()-1;
			int exchange_times = 0;
			while(begin<end){
				if (str.charAt(begin)=='1'&&str.charAt(end)=='0') {
					exchange_times++;
					//記得移動下標
					begin++;
					end--;
				}
				if (str.charAt(end)=='1') {
					end--;
				}
				if (str.charAt(begin)=='0') {
					begin++;
				}
			}
			result.add(exchange_times);
		}
		for(int j=0;j<dataLength;j++){
			System.out.println(result.get(j));
		}
		//關閉scanner
		scanner.close();
	}
	//方法描述:遍歷統計字符串中0的個數n,然後統計前n個字符中1的個數m,m即爲最小交換次數
	public void getMinExchange01Method2() {
		Scanner scanner = new Scanner(System.in);
		int dataLength = scanner.nextInt();
		scanner.nextLine();
		//保存結果
		Vector<Integer> result = new Vector<>();
		for(int i=0;i<dataLength;i++){
			String str = scanner.nextLine();
			int numsOf0 = 0;
			int numsOf1 = 0;
			for(int j=0;j<str.length();j++){
				if (str.charAt(j)=='0') {
					numsOf0++;
				}
			}
			for(int k=0;k<numsOf0;k++){
				if (str.charAt(k)=='1') {
					numsOf1++;
				}
			}
			result.add(numsOf1);
		}
		for(int i=0;i<dataLength;i++){
			System.out.println(result.get(i));
		}
		scanner.close();
	}
	public static void main(String[] args) {
		counts01 counts01 = new counts01();
		counts01.getMinExchange01Method1();
		//counts01.getMinExchange01Method2();
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章