Leetcode: First Unique Character in A String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. We clearly use a Hashmap here. Here are the examples, and I may assume a string only contains lowercase English letters.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
With the characters 'L' and 'V', respectively. Case being closed, We definitely need to use a HashMap to answer this question.
It uses either a HashMap or dictionary and marks everything that occurs in the characters.
Here's the code:
class Solution {
public int firstUniqChar(String s) {
//occurances of characters for the alphabet
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
int n = s.length();
//iterate through each character of string, and put occurance
for(int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDeafult(c,0) + 1);
}
//get the first occurance
for(int i = 0; i < n; i++) {
if(count.get(s.charAt(i)) == 1) return i;
}
//no occurences occur
return -1;
}
}
The time complexity for this code is O(N) and the space complexity is O(1) because the English Alphabet contains 26 letters.
Here's the code in Python:Counter is the hash map, and enumerates iterates through the hash map.


Comments
Post a Comment