Welcome to today's lesson, where we'll explore an interesting problem-solving approach called the "First Non-Repeating Character"! This concept is essential for beginners and intermediates alike, as it helps you understand data structures and algorithms better. Let's dive in!
Given a string, find the first non-repeating character in it. If no non-repeating character exists, return an empty string.
For example, for the string "abbacbb", the first non-repeating character is "a".
To solve this problem, we'll create a hash table (also known as a dictionary or map) to store the characters in the string and their respective counts. After that, we'll iterate through the string and check for characters with count 1 (i.e., non-repeating characters).
Here's a Python implementation:
def first_non_repeating(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char, count in char_count.items():
if count == 1:
return char
return "" # No non-repeating characters foundIn the code above, we first initialize an empty dictionary char_count. Then, we iterate through the string s and update the dictionary with the count of each character. After that, we iterate again and return the first character with a count of 1. If no such character is found, we return an empty string.
What data structure is used in the Python solution to store character counts?
Stay tuned for more lessons on Data Structures and Algorithms! šš»