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;
}
}
}
}
Top comments (0)