问题描述:
给定一个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();
}
}