题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
http://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int[] temp = new int[26]; char[] chars = str.toCharArray(); for(int i = 0; i < chars.length;i++){ //统计各字母出现的次数 int index = chars[i] - 97; 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);
}
}