删掉字符串中出现次数最少的字符

package test;


import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;


public class a23 {


/**

* @param args

*/

public static void main(String[] args) {

String str = "aaabbdddcc";


String r = getStr(str);

char[] rt = r.toCharArray();

for (char c : rt) {

str = str.replace(c+"", "");

}

System.out.println("结果:" + str);

}


public static String getStr(String str){

Map<String,Integer> map = new TreeMap<String, Integer>();

char[] st = str.toCharArray();

for (char c : st) {

if(map.get(c+"") != null){//如果key 已出现过一次,则value值加1

map.put(c+"", map.get(c+"") + 1);

}else{

map.put(c+"", 1);

}

}

Integer temp = null;  //用于存放最小value值

String tempStr = "";  //用于存放最小值对应的key值,可以存放多个

for (Entry<String, Integer> c : map.entrySet()) {

if(temp != null && temp > c.getValue()){//如temp大于value,则替换temp值,并存放对应的key值

temp = c.getValue();

tempStr = c.getKey();

}else if(temp == null){

temp = c.getValue();

}else if(temp != null && temp == c.getValue()){//如最小值相同,则只存对应的key值

tempStr += c.getKey();

}

}

System.out.println("出现次数较少的字符:" + tempStr);

return tempStr;

}

}


你可能感兴趣的:(字符串,删掉)