Find the first non-repeating character in a given string.
Given a string, find the first non-repeating character in it. For example, if the input string is “GeeksforGeeks”, then the output should be ‘f’ and if the input string is “GeeksQuiz”, then the output should be ‘G’. Example input: "GeeksforGeeks" Example output: 'f'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string input = "GeeksforGeeks"; char output = FirstNonRepeatingChar(input); Console.WriteLine(output); Console.ReadLine(); } static char FirstNonRepeatingChar(string input) { //create a dictionary to store the character and the number of times it appears in the string Dictionary<char, int> charCount = new Dictionary<char, int>(); //loop through the string and add each character to the dictionary foreach (char c in input) { if (charCount.ContainsKey(c)) { charCount[c]++; } else { charCount.Add(c, 1); } } //loop through the string again and return the first character that has a count of 1 foreach (char c in input) { if (charCount[c] == 1) { return c; } } //if no character has a count of 1, return null return '\0'; } } }
The candidate's solution correctly solves the problem and uses a reasonable approach.
Evaluated at: 2022-12-04 12:15:34