HJ23 删除字符串中出现次数最少的字符
描述
实现删除字符串中出现次数最少的字符,若出现次数最少的字符有多个,则把出现次数最少的字符都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。
数据范围:输入的字符串长度满足 1≤𝑛≤20 1≤n≤20 ,保证输入的字符串中仅出现小写字母
输入描述:
字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。
输出描述:
删除字符串中出现次数最少的字符后的字符串。
示例:
输入:aabcddd 输出:aaddd
分析:
1.使用HashMap集合存储数据。
2.Collections类收集集合的value值和最小值。
代码:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s=sc.nextLine();
if(s.length()>20||s.length()<1){
System.out.println("非法输入!");
return;
}
for (int i = 0; i < s.length(); i++) {
if(!(s.charAt(i)>='a'&&s.charAt(i)<='z')){
System.out.println("非法输入!");
return;
}
}
HashMap<Character,Integer> map=new HashMap<>();
char c;
for (int i = 0; i < s.length(); i++) {
c=s.charAt(i);
if(map.containsKey(c)){
map.replace(c,map.get(c)+1);
}else {
map.put(c,1);
}
}
//最小值
Collection<Integer> values = map.values();
int min=Collections.min(values);
Set<Map.Entry<Character,Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
Character key = entry.getKey();
Integer value = entry.getValue();
if(value==min){
s=s.replace(key+"","");
}
//System.out.println(key + " -- " + value);
}
System.out.println(s);
}
}
大佬代码:
大佬写的简单一点。
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String s = scanner.nextLine();
char[] chars = s.toCharArray();
//统计每个字母的数量
HashMap<Character, Integer> map = new HashMap<>();
for (char aChar : chars) {
map.put(aChar, (map.getOrDefault(aChar, 0) + 1));
}
//找到数量最少的字符数量
Collection<Integer> values = map.values();
Integer min = Collections.min(values);
//用空字符串替换该字母
for (Character character : map.keySet()) {
if (map.get(character) == min){
s = s.replaceAll(String.valueOf(character), "");
}
}
System.out.println(s);
}
}
}
使用Math.min函数
import java.util.*;
public class Main {
public Main() {
}
public String delete(String str) {
// Map记录每个字母的次数
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
// 快速找出最少次数
int min = Integer.MAX_VALUE;
for (int times : map.values()) {
min = Math.min(min, times);
}
StringBuilder res = new StringBuilder();
for (char ch : str.toCharArray()) {
if (map.get(ch) != min) {
res.append(ch);
}
}
return res.toString();
}
public static void main(String[] args) {
Main solution = new Main();
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
String res = solution.delete(str);
System.out.println(res);
}
}
}