Write a method to find the first non-repeating character from a String?
GIT URL: Java Solution to find the first non-repeating character from a String
Solution 1: Using LinkedHashMap.
1). Create a LinkedHashMap, which will maintain the count.
2). Convert the input string into a char array, start iterating it and add each character in LinkedHashMap. If the character is already present in LinkedHashMap, increment the count.
3). Loop through LinkedHashMap and find the character with the count as 1.
Solution 2: Finds first non repeated character in a String in just one pass.
1). To cut down the iteration, we need Set and a List, set will contain repeating chars and List will contain non repeating chars.
2). We will start iterating the input String, if the char is present in nonRepeating list, remove it and add it in repeating Set, else add the character in nonRepeating List.
3). At the end return the 1st element from nonRepeating List.
-K Himaanshu Shuklaa..
No comments:
Post a Comment