Thursday, October 2, 2014
HashMap
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FindDuplicateInString {
public void findDuplicateInString(String str){
char[] chars = str.toCharArray();
Map<Character,Integer> map = new HashMap<Character,Integer>();
// constructs map
for (char ch : chars){
if (map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}else{
map.put(ch,1);
}
}
// print out duplicate char
Set<Character> keys = map.keySet();
for (Character key : keys){
if (map.get(key)>1){
System.out.println("duplicate char: "+key);
}
}
}
public static void main(String[] args){
FindDuplicateInString duplicate = new FindDuplicateInString();
duplicate.findDuplicateInString("java");
}
}
OUTPUT:
duplicate char: a
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment