Saturday, August 13, 2016

Easy way to find Duplicate character in String Java

Change Snippet Background Color

  
    private static boolean findDuplicate(String str){

        Map map = new HashMap<>();
        char[] getChar = str.toCharArray();
        for(Character isDuplicate:getChar){
            if(map.containsKey(isDuplicate)){
               // plus 1 if found same character     
               map.put(isDuplicate, map.get(isDuplicate)+1);
            } else {
               // add 1 to new Character
               map.put(isDuplicate, 1);
            }
        }
        Set keys = map.keySet();
        for(Character isDuplicate:keys){
            if(map.get(isDuplicate) > 1){
                //found more than 1
                return true;
            }
        }

        return false;
    }

  

No comments:

Post a Comment