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.


import java.util.HashMap;
import java.util.Map;

public class KthNonRepeatChar {

   private static char getKthNonoRepeatChar(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 void main(String[] args) {
      String str = "thisissamplestring";
      int kthNonRepeat = 4;
      char character = getKthNonoRepeatChar(str,kthNonRepeat);
      System.out.println(character);
   }
}

1 comment:

  1. Map will not give you order which you need. Not work for very Long String.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...