繁体   English   中英

迭代器在打印值时缺少TreeSet中的一个元素

[英]Iterator is missing one element from the TreeSet while printing value

我正在研究必须从输入中计算重复字符的出现并按降序打印大于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 ;
    }

问题是您在CharItem中实现了Comparator。 如果您的CharItem在字符串中出现的次数相同,则它们相等。 因此,您必须考虑到您的字符。 您应该将比较器更改为:

@Override
public int compareTo(CharItem b) {
  int occurences = Integer.compare(b.count, count);
  if (occurences == 0) {
    return Character.compare(ch, b.ch);
  }
  return occurences;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM