我正在处理问题,我必须从输入中计算出重复字符的出现次数,然后按降序打印那些字数大于n次的字符串。
我已编写代码,但由于我的迭代器缺少一个字符,即使它符合标准
示例输入是:
abbababbabkeleeklkel
3 (=N) // where N=3
示例输出为:
bae
as
1)b appears 6 times
2)a appears 4 times
3)e appears 4 times
代码是:
private static void printDuplicate(String s, int times){
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
boolean isAppear = true;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int count = 1;
if(tm.containsKey(ch)){
count=tm.get(ch) + 1;
}
tm.put(ch, count);
}
StringBuilder temp = new StringBuilder("");
TreeSet<CharItem> ts = new TreeSet<CharItem>();
Iterator<Character> it = tm.descendingKeySet().iterator();
while (it.hasNext()){
char ch = (char) it.next();
int count = tm.get(ch);
CharItem ci= new CharItem(ch, count);
ts.add(ci);
System.out.println("Character is " + ch + " count is " + ci.getCount());
}
Iterator<CharItem> it2 = ts.iterator();
while(it2.hasNext()){
CharItem ci=it2.next();
System.out.println("Ci key value " + ci.getCh() + " and count is " + ci.getCount());
if(ci.getCount() >times){
isAppear=false;
temp.append(ci.getCh());
}
}
if(isAppear){
System.out.println("NONE");
}
else
System.out.println(temp);
}
}
但我收到的输出是“be
”。一些缺少的角色。
有人可以告诉我可能是什么问题吗?
CharItem是一个实现Comparable的类:
class CharItem implements Comparable<CharItem>{
private int count;
private char ch;
public CharItem(char c, int i){
count = i;
ch = c;
}
public char getCh() {
return this.ch;
}
public int getCount() {
return this.count;
}
@Override
public int compareTo(CharItem b) {
return b.count - this.count ;
}
答案 0 :(得分:1)
问题是在CharItem中实现Comparator。如果它们在字符串中具有相同数量的出现,则它们的CharItems是相等的。所以你必须考虑你的char。您应该将比较器更改为:
@Override
public int compareTo(CharItem b) {
int occurences = Integer.compare(b.count, count);
if (occurences == 0) {
return Character.compare(ch, b.ch);
}
return occurences;
}