题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
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);
}
}
}