Java - find the first non-repeating character in String

find the first non-repeating character in String

Description

find the first non-repeating character in String

Test cases

You can use the following test cases to verify your code logics.

ID Input Ouput
1abcabce e
2geek for queek g
3abc a

Code template

Cut and paste the following code snippet to start solve this problem.

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

public class Main{
  public static void main(String[] args) {
    String input = "geek for queek";
    found(input);
    
    input = "abcabce";
    found(input);

    input = "abc";
    found(input);
  }
  public static void found(String str) {
    //your code here
  }
}

Answer

Here is the answer to the question above.

Demo

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

public class Main{
  public static void main(String[] args) {
    String input = "geek for queek";
    found(input);/*from  w w  w.j a v  a2  s.c o m*/
    
    input = "abcabce";
    found(input);

    input = "abc";
    found(input);
  }
  public static void found(String str) {
    Map<Character, Integer> hm = new LinkedHashMap<>();
    for (int i = 0; i < str.length(); i++) {
      if (hm.containsKey(str.charAt(i))) {
        hm.put(str.charAt(i), hm.get(str.charAt(i)) + 1);
      } else {
        int intial = 1;
        hm.put(str.charAt(i), intial);
      }
    }
    for (Map.Entry<Character, Integer> entry : hm.entrySet()) {
      if (entry.getValue() == 1) {
        System.out.println("first non repeating character is:"+ entry.getKey());
        break;
      }
    }
  }
}