Java 删除字符串中出现次数最少的字符
方法一
1 import java.util.HashMap; 2 import java.util.Map; 3 import java.util.Scanner; 4 5 public class Main{ 6 public static void main(String[] args) { 7 Scanner sc = new Scanner(System.in); 8 while(sc.hasNext()) { 9 String dis = del(sc.nextLine()); 10 System.out.println(dis); 11 } 12 } 13 14 public static String del(String str) { 15 //统计字符出现的次数 16 Map<Character, Integer> map = new HashMap<>(); 17 for(char c: str.toCharArray()) { 18 if (map.containsKey(c)) { 19 map.put(c, map.get(c) +1); 20 } else { 21 map.put(c, 1); 22 } 23 } 24 //遍历记录最小出现次数 25 int min = Integer.MAX_VALUE; 26 for (Map.Entry<Character, Integer> entry: map.entrySet()) { 27 if(entry.getValue() < min) { 28 min = entry.getValue(); 29 } 30 } 31 32 //删除字符 33 for (Map.Entry<Character, Integer> entry: map.entrySet()) { 34 if (entry.getValue() == min) { 35 str = str.replace(entry.getKey() + "", ""); 36 } 37 } 38 return str; 39 } 40 }
方法二
1 import java.io.*; 2 3 4 public class Main{ 5 6 public static void main(String[] args) throws IOException{ 7 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 String str = null; 9 StringBuilder sb = new StringBuilder(); 10 while((str = br.readLine()) != null){ 11 char[] chArr = str.toCharArray(); 12 int[] countArr = new int[chArr.length]; 13 //统计每一位上字符在整个字符串中出现的次数 14 for(int i=0;i< chArr.length ;i++){ 15 for(int j = 0; j<chArr.length;j++){ 16 if(chArr[i] == chArr[j]){ 17 countArr[i] += 1; 18 } 19 } 20 } 21 22 //假设第一位字符对应的次数最小,能找到更小的则替换 23 int min = countArr[0]; 24 for(int id : countArr){ 25 if(id < min){ 26 min = id; 27 } 28 } 29 30 //遍历countArr中字符出现次数,不等于最小的则将对应字符添加到sb中 31 for(int i = 0;i< countArr.length;i++){ 32 if(countArr[i] != min){ 33 sb.append(chArr[i]); 34 } 35 } 36 sb.append("\n"); 37 } 38 System.out.print(sb.toString()); 39 } 40 }
浙公网安备 33010602011771号