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

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

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 str = in.next();
        int[] count = new int[26];  //每个字母出现次数
        char[] letter = str.toCharArray();
        for (char c : letter){
            count[c - 'a']++;
        }
        int min = 20;
        int minCount = 0;  //有几个最少字符
        int[] minIndex = new int[20];  //最少字符的下标
        for (int i = 0; i < 26; i++) {
            if (count[i] == 0) continue;
            if (count[i] < min) {
                min = count[i];
                minIndex[0] = i;
                minCount = 1;
            } else if (count[i] == min) {
                minIndex[minCount++] = i;
            }
        }
        //跳过最少字符输出
        for (char c : letter) {
            boolean flag = false;
            for (int i = 0; i < minCount; i++) {
                int index = minIndex[i];
                if (c - 'a' == index) {
                    flag = true;
                    continue;
                }
            }
            if (!flag) System.out.print(c);
        }
    }
}

全部评论

相关推荐

04-28 15:42
郑州大学 C++
找工作勤劳小蜜蜂:网易这几个月在大面积裁员,外包岗全退,今年网易收缩严重,建议慎重考虑网易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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