
The objective of this task is to process a given string s and find the first character that does not repeat anywhere else in the string. Once identified, the index of this non-repeating character is to be returned. If every character within the string repeats, the function should return -1. This problem tests efficient string processing with attention to time and space constraints.
Input:
Output:
Explanation:
Input:
Output:
Explanation:
Input:
Output:
Explanation:
1 <= s.length <= 10^5s consists of only lowercase English letters.To solve this efficiently:
Build a frequency map:
Scan for the first unique character:
Edge Case:
-1.For s = "sampletext":
{'s': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1, 'e': 3, 't': 2, 'x': 1}'s' at index 0.For s = "lovecodehere":
{'l': 1, 'o': 2, 'v': 1, 'e': 4, 'c': 1, 'd': 1, 'h': 1, 'r': 1}'v' at index 2.For s = "aabb":
{'a': 2, 'b': 2}-1.This Java program finds the first unique character in a given string. The method firstUniqueCharacter within the Solution class accomplishes this by using a HashMap to count the frequency of each character in the string.
Follow these steps to understand the solution:
HashMap named charFrequency to store the characters and their corresponding frequencies.HashMap with each character's count using the getOrDefault method, which returns the existing value if the character is already in the map, or 0 if not, and then increments by 1.This approach ensures that each character is processed in constant time, making it efficient even for longer strings.
0 Comments
Be the first to comment and share your perspective with the community.