Problem: Given a string, find the first non-repeating character in it.
For example:
For example:
Input s = "stress" Output: t Input: s = "InterviewDesk" Output: IMethod 1: We know a non repeated character occurs only once in the string, so if we store the number of times each alphabet appears in the string, it would help us identifying which characters are non repeated characters in the string. Following is the algorithm:
- Scan the string from left to right and construct the count array.
- Again, scan the string from left to right and check for count of each character, if you find an element who's count is 1, return it.
import java.util.HashMap; class practice { public static int firstNonRepeatedCharacter(String s) { /* Auxilary array to store the frequency */ char count[] = new char[256]; for(int i=0; i < s.length(); i++) { count[s.charAt(i)]++; } /* search count in order of string s */ for (int i = 0; i < s.length(); i++) { if(count[s.charAt(i)] == 1) return i; } return -1; } /* driver method */ public static void main(String[] args) { String s = "InterviewDesk"; int ind = firstNonRepeatedCharacter(s); System.out.println(ind == -1 ? "All characters repeating" : "The first non repeated character is : " + s.charAt(ind)); } }Output:
The first non repeated character is : ITime Complexity: O(2*n)