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

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

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

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

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()){
        String str = sc.nextLine();
        char[] chars = str.toCharArray();
        //首先去重
        List<Character> list = new ArrayList<>();
        Map<Character,Integer> map = new HashMap<>();
        for (char c : chars) {
            list.add(c);
        }
        List<Character> newList = new ArrayList<>();
        newList = list.stream().distinct().collect(Collectors.toList());
        //判断每个字符出现的次数
        for (int i = 0; i < newList.size(); i++) {
            int count = 0;
            for (int k = 0; k < chars.length;k++){
                if(chars[k]==newList.get(i)){
                    count++;
                }

            }
                map.put(newList.get(i),count);
        }
        //求出现次数最少的字符
        int min = map.get(list.get(0));
        Set<Character> keySet = map.keySet();
        for (Character c : keySet) {
            int count = map.get(c);
            if(count < min){
                min = count;
            }
        }
        List<Character> minChar = new ArrayList<>();
        for (Character c : keySet) {
            if(map.get(c)==min){
                minChar.add(c);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if(minChar.contains(list.get(i))){
                list.remove(i);
                i = -1;
            }
        }
        String subString = "";
        for (Character c : list) {
            subString = subString+c;
        }
        System.out.println(subString);
    }
}

}

全部评论

相关推荐

10-30 22:18
已编辑
毛坦厂中学 C++
点赞 评论 收藏
分享
我已成为0offer的糕手:别惯着,胆子都是练出来的,这里认怂了,那以后被裁应届被拖工资还敢抗争?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务