删除字符串中出现次数最少的字符
- 热度指数:2243时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。
输入描述:
字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。
输出描述:
删除字符串中出现次数最少的字符后的字符串。
输入例子:
abcdd
输出例子:
dd
代码
package com.huawei;
import java.io.BufferedInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class 删除字符串中出现次数最少的字符 {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
while(sc.hasNext()){
String nextLine = sc.nextLine();
System.out.println(deleteMinChar(nextLine));
}
}
private static String deleteMinChar(String nextLine) {
//统计
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if(!map.containsKey(c)){
map.put(c, 1);
}else{
map.put(c, map.get(c)+1);
}
}
int minCount = 21;
for(Map.Entry<Character, Integer> entry:map.entrySet()){
if(entry.getValue()<minCount){
minCount = entry.getValue();
}
}
char[] char_array = new char[nextLine.length()];
int index_char_array = 0;
for (int i = 0; i < nextLine.length(); i++) {
if(map.get(nextLine.charAt(i))>minCount){
char_array[index_char_array++] = nextLine.charAt(i);
}
}
return new String(char_array).trim();
}
}