Baidu笔试-01序列排序的交换次数

本文介绍两种高效的字符串翻转算法:一种使用双指针技术仅需遍历一次;另一种通过计算特定字符数量实现优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:


问题分析:

解法一:设置双指针,start,end;当data[start]=‘1’,data[end]=’0’时,表示需要进行交换,次数加1;否则data[end]=’1’则前移end指针;data[start]=‘0’则后移start指针;

该算法仅需遍历一次

解法二:先遍历一次计算字符数组中0的个数zero,再计算前zero个字符中1的个数,即是要交换到后面的字符(仅需遍历到zero个字符即可);

代码:

解法一:

import java.util.Scanner;

public class Main1 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		//记录有多少组数据
		int data_length = in.nextInt();
		
		//第一层循环
		for (int i = 0; i < data_length; i++) {
			String str = in.next();
			char[] chars = str.toCharArray();
			int start = 0;
			int end = chars.length - 1;
			int result = 0;
			while(start < end)
			{
				if (chars[start] == '1' && chars[end] == '0') {
					++result;
					start ++;
					end --;
				}
				else 
				{
					if(chars[end] == '1')
					{
						end --;
					}
					if(chars[start] == '0')
					{
						start ++;
					}
				}
			}
			System.out.println(result);
		}
	}
}

解法二:
import java.util.Scanner;

public class Main1 {

	public static void main(String args[]) {

		Scanner in = new Scanner(System.in);	

		int n = in.nextInt();
		
		while (n-- != 0) {
			
			int zero = 0, swap = 0;
			String str = in.next();
			
			for (int i = 0; i < str.length(); i++)
				if (str.charAt(i) == '0')
					zero++;
			
			for (int i = 0; i < zero; i++)
				if (str.charAt(i) == '1')
					swap++;
			
			System.out.println(swap);
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值