Saturday, November 21, 2015

Find first non repeating character from a string

Given a string find first non repeating character from a string.

We can use HashMap to find the duplicates. To find out first non repeated character, iterate the string to find character which is not repeated. 
 
public class Solution{
    public static void FindFirstNonRepeatingChar(String input){
        if(input.length() > 0){
            HashMap charMap = new HashMap<>();
            for(char ch : input.toCharArray()){
                if(charMap.containsKey(ch))
                    charMap.put(ch, Boolean.TRUE);
                else
                    charMap.put(ch, Boolean.FALSE);
            }

            for (char ch : input.toCharArray()){
                if(charMap.get(ch) == Boolean.FALSE) {
                    System.out.println("First Non Repeating Character : " + ch);
                    return;
                }
            }
        }
        System.out.println("Couldn't find Non Repeating Character");
    }

    public static void main(String[] args){
        FindFirstNonRepeatingChar("asdffdsa");
    }
}

Comments are welcome.

No comments:

Post a Comment