class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
int index = (int)s.charAt(i) - 97;
count[index]++;
}
for (int i = 0; i < s.length(); i++) {
int index = (int)s.charAt(i) - 97;
if (count[index] == 1) return i;
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> count = new HashMap<>();
for (char c : s.toCharArray()) {
count.put(c, count.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (count.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
| 방법 | 시간 | 공간 | 특징 |
|---|---|---|---|
| 배열 | O(n) | O(1) | 최적, 소문자만 |
| HashMap | O(n) | O(n) | 유니코드 대응 |
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
개선: 97 → 'a', 불필요한 캐스팅 제거
고유 문자 찾기 = 빈도수 배열 + Two Pass
#LeetCode #HashMap #FrequencyCount #String #Easy #배열