在字符串中查找重复的字符。

huangapple go评论75阅读模式
英文:

Find Duplicate character in a String

问题

public static String duplicate(String str) {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    for(int i = 0; i < str.length(); i++) {
        if(map.containsKey(str.charAt(i))) {
            return String.valueOf(str.charAt(i));
        }
        map.put(str.charAt(i), i);
    }
    return "-1";
}
英文:

I want to return a duplicated char in a string or "-1" if not found.

The problem is my compiler asks me to change the return type to char at this line return str.charAt(i); but I dont want to use char return type, I want to use String as return type. Can you help me please?

public static String duplicate(String str) {

	HashMap&lt;Character, Integer&gt; map = new HashMap&lt;Character, Integer&gt;();
	for(int i=0; i&lt;str.length(); i++) {
        if(map.containsKey(str.charAt(i))) {
            return str.charAt(i);
        }
        map.put(str.charAt(i), i);
    }
    return &quot;-1&quot;;
}

答案1

得分: 0

使用 Character.toString()

public static String duplicate(String str) {

    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    for(int i=0; i<str.length(); i++) {
        if(map.containsKey(str.charAt(i))) {
            return Character.toString(str.charAt(i));
        }
        map.put(str.charAt(i), i);
    }        
    return "-1";
}
英文:

Use Character.toString()

public static String duplicate(String str) {

    HashMap&lt;Character, Integer&gt; map = new HashMap&lt;Character, Integer&gt;();
    for(int i=0; i&lt;str.length(); i++) {
        if(map.containsKey(str.charAt(i))) {
            return Character.toString(str.charAt(i));
        }
        map.put(str.charAt(i), i);
    }        
    return &quot;-1&quot;;
}

huangapple
  • 本文由 发表于 2020年7月25日 02:02:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63079127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定