![]() |
VOOZH | about |
Given a string s consisting of lowercase letters, for each position i in the string (0 ≤ i < n), find the first non-repeating character in the prefix s[0..i]. If no such character exists, use '#'.
Examples:
Input: s = "aabc"
Output: a#bb
Explanation:
After ("a"): First non-repeating character is 'a'.
After ("aa"): No non-repeating character, so '#'.
After ("a#b"): First non-repeating character is 'b'.
After ("aabc"): Non-repeating characters are 'b' and 'c'; 'b' appeared first, so 'b'.
Result = a#bbInput: s = "bb"
Output: b#
Explanation:
After ("b"): First non-repeating character is 'b'.
After ("bb"): No non-repeating character, so '#'.
Result = b#
Table of Content
This approach maintains a frequency count of each character using a vector. For each character in the string, it scans from the beginning to find the first non-repeating character by checking the frequency of each character up to that point. If a non-repeating character is found, it is appended to the result; otherwise,
#is appended when no such character exists. This process ensures that the first non-repeating character is identified at each step.
a#bb
We use a count array of size 26 to track character frequencies and a queue to maintain their order of appearance. For each new character, we update its frequency and push it into the queue. Then, we remove characters from the front of the queue until the first non-repeating character is found, or the queue becomes empty.
a#bb
We maintain a frequency array to count occurrences and another array to store the first position of each character. While processing the string, we update frequencies and then check which character has frequency 1 and appeared earliest. That character becomes the current answer; if none exists, we place a '#'.
a#bb