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;
}
}
'๐ป Coding Problems Solving > Hash | HashMap' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Group Anagrams (0) | 2023.07.18 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ๋ฐฉ๋ฌธ๊ธธ์ด (์๋ฐ java) (0) | 2023.03.12 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ์ฃผ์ฐจ ์๊ธ ๊ณ์ฐ (java) (0) | 2023.03.04 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 [3์ฐจ] ์์ถ (0) | 2022.04.25 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ์ ํ๋ฒํธ ๋ชฉ๋ก (0) | 2022.04.12 |
์ต๊ทผ๋๊ธ