I read of a job interview question to write some code for the following:
Write an efficient function to find the first nonrepeated character in a st
In Java, 1)Create the Character count hashmap. For each character,if there is no value stored in the character,set it to 1. Else increment the value of the character by 1 .
2)Then I Scanned the String for each character. Return character if the count in hashmap is 1 . If no character has count 1 ,then return null.
package com.abc.ridhi;
import java.util.HashMap;
import java.util.Scanner;
public class FirstNonRepeated {
public static void main(String[] args) {
System.out.println(" Please enter the input string :");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char c = firstNonRepeatedCharacter(s);
System.out.println("The first non repeated character is : " + c);
}
public static Character firstNonRepeatedCharacter(String str) {
HashMap map1 = new HashMap();
int i, length;
Character c;
length = str.length();
// Scan string and build hashmap
for (i = 0; i < length; i++) {
c = str.charAt(i);
if (map1.containsKey(c)) {
// increment count corresponding to c
map1.put(c, map1.get(c) + 1);
} else {
map1.put(c, 1);
}
}
// Search map in order of string str
for (i = 0; i < length; i++) {
c = str.charAt(i);
if (map1.get(c) == 1){
return c;
}
}
return null;
}
}