题解 | #删除字符串中出现次数最少的字符#

删除字符串中出现次数最少的字符

https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String ipt = in.nextLine();
        int[] times = new int[27];
        for(char c : ipt.toCharArray()){
            times[c-'a'] ++;
        }
        int min = Integer.MAX_VALUE;
	  // 最小的次数是几
        for(int i : times){
            if(i!=0)
                min = Math.min(min,i);
        }

        
	  // 找出出现次数等于最小次数的这些字符
        HashSet<Character> minTimeChars = new HashSet();
        for(int i = 'a'; i <='z';i++){
            if(times[i-'a'] == min){
                minTimeChars.add((char)i);
            }
        }
		//求差集
        StringBuilder sb = new StringBuilder();
        for(char c : ipt.toCharArray()){
            if(!minTimeChars.contains(c)){
                sb.append(c);
            }
        }
        System.out.println(sb.toString());
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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