Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active July 13, 2023 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/36411600b2db2ac5e3b2a681686dc1f4 to your computer and use it in GitHub Desktop.
Save thmain/36411600b2db2ac5e3b2a681686dc1f4 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
public class FirstNonRepeatingCharacter {
public static Character getCharacter(String input){
//remove all the spaces
input = input.replaceAll(" ", "");
Character nonRptChar = null;
//Will store each character and it's count
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i <input.length(); i++) {
Character chr = input.charAt(i);
int count = map.getOrDefault(chr, 0);
map.put(chr, count+1);
}
//Iterate the string and return the character for which the count is 1 in map
for (int i = 0; i <input.length() ; i++) {
if(map.get(input.charAt(i))==1){
nonRptChar = input.charAt(i);
break;
}
}
return nonRptChar;
}
public static void main(String[] args) {
String input = "tutorial horizon";
Character result = getCharacter(input);
if(result!=null){
System.out.println("First Non Repeating Character in '"+input+"' is: " + result);
}else{
System.out.println("No Non Repeating Character found");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment