Home
Refer
Jobs
Alumni
Resume
Notifications

Write a program in Java to find the first non-repeated character in a given string.

🚀 Best Answers Get Featured in our LinkedIn Community based on Your Consent, To Increase Your Chances of Getting Interviewed. 🚀

Sure, here is a possible answer for the given query:

Program to find the first non-repeated character in a string using Java

Here is a sample Java program that finds the first non-repeated character in a given string:

public static char findFirstNonRepeatedChar(String str) {
Map<
Character, Integer>
charCountMap = new LinkedHashMap<
>
();
for (char ch :
str.toCharArray()) {
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<
Character, Integer>
entry :
charCountMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0';
}

The above program uses a LinkedHashMap to keep track of the count of each character in the string, in the order of their appearance. Then it iterates over the map entries and returns the first character whose count is 1, which means it is non-repeated.

To test the program, you can call the above method with a string argument:

String input = "abbcdecfg";
char result = findFirstNonRepeatedChar(input);
System.out.println("The first non-repeated character in " + input + " is " + result);

The output of the above program would be:

The first non-repeated character in abbcdecfg is a

You can further optimize the program by using a HashSet to keep track of the repeated characters and a separate variable to store the position of the first non-repeated character found so far.

Here are some relevant resources that you can refer to for more information:

I hope this helps you prepare for your interview for the DET-Associate Software Engineer-GDSF02 role at EY GDS. Good luck!

© 2024 Referral Solutions, Inc. Incorporated. All rights reserved.