题解 | 小红的双生串

小红的双生串

https://www.nowcoder.com/practice/099d6681234d4e3e95c0e0ade31929da?tpId=37&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=&judgeStatus=1&tags=593&title=&gioEnter=menu

import java.util.*;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.next();
		  	//对半数量
            int num = a.length()/2;
		  	//截取左右半边
            String tmpL_source = a.substring(0,num);
            String tmpR_source = a.substring(num);
		  	//初始化次数数组,此处128为了避免超过边界
            int[] pNumL = new int[128];
            int[] pNumR = new int[128];
		  	//根据ASII码天然定位优势,记录对应字符出现的次数
            for(int i=0;i< tmpL_source.length();i++){
                pNumL[tmpL_source.charAt(i)]++;
            }
            for(int i=0;i< tmpR_source.length();i++){
                pNumR[tmpR_source.charAt(i)]++;
            }
		  
		  	//按出现的次数低到高排序
            Arrays.sort(pNumL);
            Arrays.sort(pNumR);
            //最终更改字符次数为:左侧总长度-左侧最多字符数+右侧总长度-右侧最多字符数
            System.out.println(tmpL_source.length()-pNumL[127]+tmpR_source.length()-pNumR[127]);
        }
    }
}

全部评论

相关推荐

有点心碎的杨桃很想润:我在美团,小道消息今年秋招之后美团可能就完全不会招日常实习了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务