题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
http://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
使用map将字符存入其中,然后遍历统计出现次数,每次遍历都取最小值,直到取到最小的一个即为出现次数最少的字符,然后遍历Map使用StingBuilder将字符拼接,忽略出现次数最小那个字符即可。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
HashMap<Character,Integer> map = new HashMap<>();
// 加入到HashMap中
for(char s : str.toCharArray()){
Integer num = map.get(s);
if(num == null) {
map.put(s,1);
}else{
map.put(s,num+1);
}
}
// 统计出现次数
int min = Integer.MAX_VALUE;
for(int count : map.values()){
min = Math.min(min,count);
}
//删除那个字符并打印输出最后的字符串
StringBuilder res = new StringBuilder();
for(char ch : str.toCharArray()) {
if(map.get(ch) != min){
res.append(ch);
}
}
System.out.println(res);
}
}