【问题标题】:method always return null when trying to find the first non-repeating character in a String方法在尝试查找字符串中的第一个非重复字符时总是返回 null
【发布时间】:2016-04-10 07:41:36
【问题描述】:

我正在尝试输出字符串中的第一个非重复字符。但是我不确定我的方法有什么问题,因为它总是返回 null。任何提示都非常受欢迎。

public static char findRepeating(String s){

        HashMap<Character, Integer> charCount= new HashMap<>();

        for (Map.Entry<Character, Integer> entry: charCount.entrySet()){
            entry.setValue(0);
        }
        int count=0;
        for (int i=0; i<s.length(); i++){
            if (charCount.containsKey(s.charAt(i))){
                count=charCount.get(s.charAt(i));
                charCount.put(s.charAt(i), count++);
            }

        }
        for (Character ch:charCount.keySet()){
            if (charCount.get(ch)==0){
                return ch;
            }
        }
        return '\0';
    }

【问题讨论】:

  • 在完全不同的上下文中.. Java 字符串不会以\0 字符结尾。另外,请编辑您的问题标题以反映您的问题。

标签: java string hashmap character


【解决方案1】:

你的问题是这个循环什么都不做

    for (Map.Entry<Character, Integer> entry: charCount.entrySet()){
        entry.setValue(0);
    }

因为地图是空的。

因此,if (charCount.containsKey(s.charAt(i))) 始终为假。如果找不到密钥,您应该添加一个 else 子句将计数初始化为 1:

        if (charCount.containsKey(s.charAt(i))){
            count=charCount.get(s.charAt(i));
            charCount.put(s.charAt(i), ++count); // changed to pre-increment
        } else {
            charCount.put(s.charAt(i), 1);
        }

另外请注意,我将count++ 更改为++count,因为count++ 返回count 的原始值,所以Map 中的值不会改变。

【讨论】:

  • 我怎样才能让它工作,所以它会打印第一个非重复字符而不是任何随机非重复字符?
  • @MonaJalal 将HashMap 替换为LinkedHashMap。这样,键将按照它们添加到 Map 的顺序进行迭代。
  • @MonaJalal BTW,你应该测试if (charCount.get(ch)==1)。该地图没有任何值为 0 的条目。
  • 订购需要LinkedHashMap的使用吗?因为 HashMap 也打印正确
  • @MonaJalal HashMap 不保证顺序。顺序由键(在您的情况下为字符)的 hashCodes 确定。对于某些输入,您可能会得到正确的输出,但您不应该依赖它。
【解决方案2】:

因为您正在遍历其中没有元素的 charcount。

Map.Entry<Character, Integer> entry: charCount.entrySet()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多