DEV Community

realNameHidden
realNameHidden

Posted on

2 1 1 1 1

Find the First Non-Repeated Character in a String

Problem:

Given a string, find the first character that does not repeat.

Example:

Input: "swiss"
Output: 'w'

Hint:

Use a LinkedHashMap to store the frequency of each character while maintaining the insertion order. Then, iterate over the map to find the first character with a count of 1.

Java Code

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

public class Test {
    public static void main(String[] args) {

        String s = "swiss";
        LinkedHashMap<Character,Integer> hm = new LinkedHashMap<>();
        for(int i=0;i<s.length();i++) {
            hm.put(s.charAt(i), hm.getOrDefault(s.charAt(i), 0)+1);
        }
        for(Map.Entry<Character, Integer> e : hm.entrySet()) {
            if(e.getValue() == 1) {
                System.out.println(e.getKey());
                break;
            }           
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay