Pages

Monday, 6 June 2016

K’th Non-repeating Character in a String using Java

1. Create an empty hash.
2. Scan input string from left to right and insert values and their counts in the hash.

for (char ch : array) {
     if(map.containsKey(ch)) {
          map.put(ch, map.get(ch)+1);
     } else {
          map.put(ch, 1);
     }
}

3. Scan input string from left to right and initialize the count by kth character and decrease it for every character has count 1 and return the character when count becomes 0.


importjava.util.HashMap;
importjava.util.Map;

public classKthNonRepeatChar {

   private static chargetKthNonoRepeatChar(String str,int kthRepeat) {
     
      char[] array = str.toCharArray();
      Map<Character, Integer> map = new HashMap<>();
      for (char ch : array) {
         if(map.containsKey(ch)) {
            map.put(ch, map.get(ch)+1);
         } else {
            map.put(ch, 1);
         }
      }

      for (char c : array) {
         if(map.get(c)==1) {
            kthRepeat --;
         }
         if(kthRepeat==0) {
            return c;
         }
      }
      return 0;
   }

   public static voidmain(String[] args) {
      String str = "thisissamplestring";
      int kthNonRepeat = 4;
      char character = getKthNonoRepeatChar(str,kthNonRepeat);
      System.out.println(character);
   }
}

No comments:

Post a Comment