June 22, 2022

Java Program to Find First Non-Repeated Character in The Given String

This post shows ways to find first non repeated character in a given String in Java. For example, if the given String is "abcdcab" then the first non repeated character is d.

There are many options to write a Java program to find first non repeated character in the given String some of them are as follows.

  1. Using LinkedHashMap
  2. Using indexOf() method of the String class
  3. Write your own logic with out using any inbuilt Java method.

Find first non repeated character using LinkedHashMap

In the solution using LinkedHashMap you can iterate the String character by character and store it in the map as a (key, value) pair where character is the key and its count is value. For every character, check in the LinkedHashMap if the key already exists, if yes then increment its count otherwise store it with count as 1.

Once all the characters are stored in the map, iterate the map to look for the first key with the value 1. That would be the first non repeated character. Here LinkedHashMap is used because it maintains the insertion order that helps if you need the first non repeated character in the String.

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class NonRepeatedChar {
  public static void main(String[] args) {
    String str = "abcdcab";
    Map<Character, Integer> charMap = storeInMap(str);
    char c = findCharInMap(charMap);
    if(c != ' '){
      System.out.println("First non repeated char in "+ str + " is " + c);
    }
  }
	
  private static Map<Character, Integer> storeInMap(String str){
    Map<Character, Integer> charMap = new LinkedHashMap<Character, Integer>();

    for(int i = 0; i < str.length(); i++){
      Character c = str.charAt(i);			
      if(charMap.containsKey(c)){
        charMap.put(c, charMap.get(c) + 1);
      }else{
          charMap.put(c, 1);
      }
    }
    return charMap;
  }
	
  private static char findCharInMap(Map<Character, Integer> charMap){
    for(Entry<Character, Integer> entry : charMap.entrySet()){
      // Find first char with count 1
      if(entry.getValue() == 1){
        return entry.getKey();
      }
    }
    return ' ';
  }
}
Output
First non repeated char in abcdcab is d

Using indexOf() method to find first non repeated character

You can also use indexOf() and lastIndexOf() method of the String class to find first non repeated character in the given String. Since indexOf() returns the index of the first occurrence of the given character and lastIndexOf() returns the index of the last occurrence of the given character in the String so the character for which index returned by both the methods is equal would be the first non repeated character.

public class NonRepeatedChar {
  public static void main(String[] args) {
    String str = "juju";
    findUsingIndex(str);
    findUsingIndex("jejune");
  }
	
  private static void findUsingIndex(String str){
    Character c = null;
    boolean flag = false;
    for(int i = 0; i < str.length(); i++){
      c = str.charAt(i);
      if(str.indexOf(c) == str.lastIndexOf(c)){
        flag = true;
        break;
      }
    }
    if(flag){
      System.out.println("First non repeated char in "+ str + " is " + c);
    }else{
      System.out.println("non repeated char not found in "+ str);
    }
  }
}
Output
non repeated char not found in juju
First non repeated char in jejune is u

Finding first non repeated char without using any inbuilt Java method

If you are asked to solve this problem without using any inbuilt Java method in any interview then you can use the given logic.

In an outer loop you will iterate the string character by character, in an inner for loop you will again iterate the String and compare the character from the outer loop with all the characters of the string. If a match is found that means the character is repeated, if no match found for the character then it is a non repeated character.

public class NonRepeatedChar {
  public static void main(String[] args) {
    String str = "juju";
    findNonRepeated(str);
    findNonRepeated("jejune");
  }
	
  private static void findNonRepeated(String str){
    //Character c = null;
    boolean foundFlag = false;
    for(int i = 0; i < str.length(); i++){ 
      foundFlag = true;
      char c = str.charAt(i);
      for(int j = 0; j < str.length(); j++){
        // If similar char found, also check for the same index  
        if(c == str.charAt(j) && j != i){
          foundFlag = false;
          break; // inner for loop
        }
      }
      if(foundFlag){
        System.out.println("First non repeated char in "+ str + " is " + c);
        break; // outer for loop
      }
    }
    if(!foundFlag){
      System.out.println("non repeated char not found in "+ str);
    }
  }
}
Output
non repeated char not found in juju
First non repeated char in jejune is u

That's all for the topic Java Program to Find First Non-Repeated Character in The Given String. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment