Sunday, October 9, 2011

Duplicate characters in a string

The function assumes that all characters are same case.
1)countChars() : list the characters and their count
2) checkIfDupChars : checks if String has duplicate characters


 public void countChars(String s){   
      if(s == null || s.length() == 0){   
        return;   
      }   
      final Map<Character, Integer> charCountMap = new HashMap<Character, Integer>();   
      for(int i = 0; i < s.length() ; i++){   
        Character c = s.charAt(i);   
        if(!charCountMap.containsKey(c)){   
          charCountMap.put(c, new Integer(1));   
        }else{   
          final int charCount = charCountMap.get(c).intValue();   
          charCountMap.put(c, new Integer(charCount + 1));   
        }   
      }   
      final Set<Character> keySet = charCountMap.keySet();   
      for(final Character c : keySet){   
        System.out.println("The character "+c+" appears "+charCountMap.get(c)+" times.");      }   
    }   


  public boolean checkIfDupChars(String s){  
         if(s == null || s.length() == 0){  
             return false;  
         }  
         List<Character> charList = new ArrayList<Character>();  
         for(int i = 0; i < s.length() ; i++){  
             Character c = s.charAt(i);  
             if(!charList.contains(c)){  
                 charList.add(c);  
             }else{  
                 return false;  
             }  
         }  
         return true;  
     }  

No comments:

Post a Comment