First non repeating character
Created on: Jan 15, 2025
Find first non-repeating character of given string.
Input: s = “geeksforgeeks” Output: ‘f’ Explanation: ‘f’ is the first character in the string which does not repeat. Input: s = “racecar” Output: ‘e’ Explanation: ‘e’ is the only character in the string which does not repeat.
public class Solution { public static char findFirst(String input) { return null; } public static void main(String[] args) { String str = "ababdc"; char c = findFirst(str); System.out.println(c); } }
Solution using Linked hash set
public static char findFirst(String input) { Set<Character> set = new LinkedHashSet<>(); for (int i = 0; i < input.length(); i++) { if(set.contains(input.charAt(i))){ set.remove(input.charAt(i)); }else { set.add(input.charAt(i)); } } return set.iterator().next(); }
d
Solution using frequency array
import java.util.Arrays; public class Solution { public static char findFirst(String input) { int[] freq = new int[26]; Arrays.fill(freq, 0); return findFirst(input, freq); } private static char findFirst(String input, int[] freq){ for(int i=0; i<input.length(); i++){ freq[input.charAt(i)-'a']++; } for(int i=0; i<input.length(); i++){ if(freq[input.charAt(i)-'a']==1){ return input.charAt(i); } } return '$'; } public static void main(String[] args) { String str = "ababdc"; char c = findFirst(str); System.out.println(c); } }
