This is the Java Program to Find the First non-repeated Character in a String
Given a string of characters, find the first non-repeated character in the string.
Example:
String x = “Hi this is Marry”
Output = ‘H’
Make two new arrays to store the frequency of each character and the indexes of there occurrences. Iterate through the string to fill the two arrays. Finally, re-iterate through the new arrays, to find the index of the minimum index of the characters whose frequency are 1.
Here is the source code of the Java Program to Find the First non-repeated Character in a String. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Find the First non-repeated Character in a String.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NonRepeatedCharacter {
// Function to find the first non-repeating character
static int firstNonRepeatingCharacter(String str){
int[] arrayCount = new int[256];
int[] arrayIndex = new int[256];
int i;
for(i=0; i<str.length(); i++){
arrayCount[str.charAt(i)]++;
arrayIndex[str.charAt(i)] = i;
}
int index = Integer.MAX_VALUE;
for(i=0; i<256; i++){
if(arrayCount[i] == 1 && arrayIndex[i] < index)
index = arrayIndex[i];
}
return index;
}
// Function to read user input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (IOException e) {
System.out.println("An I/O error occurred");
return;
}
int index = firstNonRepeatingCharacter(str);
if(index < str.length())
System.out.println("First Non Repeating Character is "
+ str.charAt(index));
else
System.out.println("Each character is repeated");
}
}
1. In function firstNonRepeatingCharacter(), two arrays arrayCount and arrayIndex are created.
2. The loop for(i=0; i<str.length(); i++) iterates through the string and counts the frequency of each character in arrayCount array and the index of the last occurence of a character in arrayIndex array.
3. The loop for(i=0; i<256; i++) iterates through the two arrays arrayCount and arrayIndex.
4. The condition if(arrayCount[i] == 1 && arrayIndex[i] < index) checks if the frequency of character is 1 and the second part looks for first non-repeating character.
Time Complexity: O(n) where n is the length of the string.
Case 1 (Positive Test Case): Enter the string Hi this is Marry First Non-Repeating Character is H Case 2 (Positive Test Case - another example): Enter the string well well finally you are here First Non-Repeating Character is f Case 3 (Negative Test Case): Enter the string WellWell Each character is repeated
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Computer Science Internship
- Check Programming Books
- Apply for Java Internship
- Check Java Books
- Practice BCA MCQs