英文:
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<Character, Integer> map = new HashMap<Character, Integer>();
for(int i=0; i<str.length(); i++) {
if(map.containsKey(str.charAt(i))) {
return str.charAt(i);
}
map.put(str.charAt(i), i);
}
return "-1";
}
答案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<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";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论