๐ป Coding Problems Solving/Hash | HashMap
[LeetCode] First Unique Character in a String
Kim_dev
2023. 7. 20. 22:34
1. ๋ฌธ์ : https://leetcode.com/problems/first-unique-character-in-a-string/description/
2. ํ์ด
์ํ๋ฒณ ๋์ค๋ฉด ๋ฌด์กฐ๊ฑด alpha - 'a' ํด์ ์ซ์๋ก ๋ง๋๋๊ฑฐ ์๊ฐํ๊ธฐ
3. ์ฝ๋
class Solution {
public int firstUniqChar(String s) {
int[] alph = new int[26];
//char -> first index pairs
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
//count char occurences
alph[c - 'a']++;
//this if statement is used for optimization
//if keySet().size() = 26, then we no longer
//call map's methods
if (map.keySet().size() < 26) {
if (!map.containsKey(c)) {
map.put(c, i);
}
}
}
int minIdx = s.length();
//finding minimum index of char, whose occurence is 1.
for (char c : map.keySet()) {
if (alph[c - 'a'] == 1) {
int idx = map.get(c);
minIdx = Math.min(minIdx, idx);
}
}
return minIdx == s.length() ? -1 : minIdx;
}
}