Learn-dsa..in 30 days!



























CC-17 : Find first non repeating character.

Description:

Given input String str, find and return the first non-repeating character in str.

Test cases and expected outputs:

Input Parameters Expected outputs
The input string is: Hello Hello World The first non repeating char is: W
The original string is: The lazy brown fox The first non repeating char is: T
The original string is: AAA There is no non repeating character

Pseudocode:

Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
The java method should accept following input parameters: str (String).
Initialize char array chars=str.toCharArray().
Initialize char array counts = new char[256]. We will use this array to store counts of characters found.
When we cast chars[idx] as integer, it coverts to a unique integer for each character. For example if chars[idx]=’H’, when we cast it as an integer it maps to 72. We can use 72 as the index of counts and increment counts[72] whenever we find character ‘H’ in chars. We can do this similarly for all other characters in chars.
Code for above is: counts[chars[idx]]++.
At the end of above loop, counts store the repetition counts for all characters in chars.
Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
Check counts[chars[idx] for each iteration, if it is equal to 1, this is the first non-repeating char in chars, Return this chars[idx] from the program.
If the above loop completes and we have not returned from the program with the first non-repeating character it means no such non repeating character exists in str. Return “” blank string from the program.

Code:

public char stringFirstNonRepeatingChar(String str) {
	char[] chars=str.toCharArray();
	char[] counts = new char[256];
	for (int idx=0; idx < str.length(); idx++) {
		System.out.println(chars[idx] + " " + (int)chars[idx]);
		counts[chars[idx]]++;
	}
	for (int idx=0; idx < str.length(); idx++) {
		if (counts[chars[idx]]==1) {
			return chars[idx];
		};
	}
	
	return '\u0000';
}

Click here to download and run code and test cases !