387-first-unique-character-in-a-string
Question
https://leetcode.com/problems/first-unique-character-in-a-string/description/
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Example:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Thought Process
- Hash Map
- Store the count for each character
- When we first encounter a character that has 1 count, w return the index
- Time complexity O(n)
- Space complexity O(1)
- String index of
- Use indexOf and lastIndexOf function from string, if the index is the same and not -1, we know there is exactly one count for this character
- Time complexity O(1)
- Space complexity O(1)
Solution
class Solution {
public int firstUniqChar(String s) {
int[] counts = new int[256];
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
counts[chars[i]]++;
}
for (int i = 0; i < chars.length; i++) {
if (counts[chars[i]] == 1) return i;
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
int res = s.length();
for (char c = 'a'; c <= 'z'; c++) {
int id = s.indexOf(c);
if (id != -1 && id == s.lastIndexOf(c)) {
res = Math.min(id, res);
}
}
return res == s.length() ? -1 : res;
}
}