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){ HashMapcharMap = 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