题目主要意思
1、删除一个字符串中出现次数最少的字符,若多个字符出现次数一样,都删除。
2、字符串需要保持原来的顺序
3、字符串只包含小写字母
4、多行输入输出
方法一:暴力法
具体做法
- 直接遍历字符串,将字符串存入到数组中,将字符串转成ASCII格式的,也就是都在128个ASCII里,设置一个26大小的数组即可,因为题目里说了只包含小写字母。
- 遍历字符串后将字符对应的ASCII的个数存入对应的数组中。
- 遍历数组找到最小的个数
- 遍历数组,如果当前字符出现的个数等于最小个数,则被替换掉。
Java代码
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str ;
while ((str = bf.readLine()) != null && !str.equals("")) {
char []chars = str.toCharArray();
// 题目所给出的都是小写字母 共计26个 a~z
int[] temp = new int[26];
for (int i = 0; i < chars.length; i++) {
//找到当前字符在数组中的位置 比如97对应的是a的ASCII码,
int index = chars[i] - 97;
temp[index] = temp[index] + 1;
}
//找到次数最少的个数
int min = Integer.MAX_VALUE;
for (int i = 0; i < 26; i++) {
// 跳过
if (temp[i] != 0) {
min = Math.min(min,temp[i]);
}
}
// 开始删除最小
for (int i = 0; i < 26; i++) {
if (temp[i] == min) {
char ch = (char) ('a' + i);
str = str.replace(ch + "", "");
}
}
System.out.println(str);
}
}
}
复杂度分析
- 时间复杂度:,需要遍历字符串和数组。
- 空间复杂度:,临时数组temp。
方法二:借助HashMap来存储
具体做法
遍历字符串,将字符存入HashMap中,在遍历HashMap找到最小的values,在遍历一遍HashMap把不等于最小values的记录,最后输出。
举例说明:aabcddd
Java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class Main {
public static String delete(String str) {
// Map记录每个字母的次数
HashMap<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
//将每个字符存入其中
map.put(ch, map.getOrDefault(ch, 1) + 1);
}
// 快速找出最少次数
int min = Integer.MAX_VALUE;
for (int times : map.values()) {
min = Math.min(min, times);
}
//最后输出的值
StringBuilder result = new StringBuilder();
for (char ch : str.toCharArray()) {
if (map.get(ch) != min) {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = bf.readLine())!=null) {
System.out.println(delete(s));
}
}
}
复杂度分析
- 时间复杂度:O(n),需要多次遍历字符串和Map,但都不存在嵌套遍历。
- 空间复杂度:O(n),借助了Map存储