How To Find The First Non-Repeated Character In a String

Dealing with Strings is required in any programming language, and most of the programming books will have a chapter on String. If you are preparing for technical interviews be prepared to get some questions on Strings. Finding the first non-repeated character is usually asked during interviews and coding tests in Java programming.
Here is an sample Java program to find first non-repeated character in a String. We are not using any of the java.util.Collection classes here, instead we just traverse a Character array multiple times until we get our desired character. Keep it as simple as it could be :)

Program "NonRepeatChar.java":
package com.examples;;

public class NonRepeatChar {
 public static void main(String[] args) {
  String str = "madam";
  char c = getFirstNonRepeatChar(str);
  System.out.println("The test string is: " + str);
  if (c == ' ') {
   System.out.println("All char are repeated..");
  } else {
   System.out.println("The first non-repeated char is: " + c);
  }
 }

 public static Character getFirstNonRepeatChar(String s) {
  char[] charStr = s.toCharArray();
  int count = 0;
  for (int i = 0; i <= charStr.length - 1; i++) {
   count = 0;
   for (int j = charStr.length - 1; j >= 0; j--) {
    if (charStr[i] == charStr[j]) {
     count++;
    }
   }
   if (count == 1) {
    return charStr[i];
   }
  }
  return ' ';
 }
}

Output with 2 different test strings:

The test string is: madam
The first non-repeated char is: d

The test string is: ramram
All char are repeated..


No comments:

Post a Comment