The program InterviewPrograms49 aims to find the first non-repeated character in a given string (s). The program uses two nested loops to compare each character of the string with every other character to count the number of occurrences (distinct) of each character.
Find the first non-repeated character in a word in Java
package com.softwaretestingo.interviewprograms; public class InterviewPrograms49 { /* wap to find the first non repeating character. */ public static void main(String[] args) { String s="minimum"; int distinct=0; for(int i=0;i<s.length();i++) { for(int j=0;j<s.length();j++) { if(s.charAt(i)==s.charAt(j)) { distinct++; } } if(distinct==1) { System.out.println(s.charAt(i)+"--"+distinct+"\n"); break; } String d=String.valueOf(s.charAt(i)).trim(); s.replaceAll(d,""); distinct=0; } } }
Output
n--1
Here’s how the program works:
- First, the given string s is initialized with the value “minimum”.
- The variable distinct is used to count the occurrences of each character and is initially set to 0.
- The program then enters a loop that iterates through each character of the string using the index i.
- Inside the outer loop, there is another loop that uses index
j
to compare each character with every other character in the string. - If the characters at indices i and j are the same, the distinct variable is incremented.
- After the inner loop finishes, the program checks if the distinct count is equal to 1, indicating that the character is non-repeating.
- If the condition is true, the program prints the non-repeating character along with its count using System.out.println().
- The program then breaks out of the loop to end the execution, as the first non-repeating character is found.
- If the condition is false (meaning the character is repeating), the program removes all occurrences of the current character from the string s using replaceAll().
- The distinct count is reset to 0.
- The program continues with the next character in the outer loop until it finds the first non-repeating character and prints its count.
In this specific case with the input string “minimum”, the program will output “n–1”, indicating that the first non-repeating character is ‘n’ and it occurs only once in the string.
Leave a Reply