1. 문제
2. 코드
import java.util.HashMap;
public class Main {
public int solution(String s) {
HashMap<Character, Integer> sH = new HashMap<>();
for (char x : s.toCharArray()) {
sH.put(x, sH.getOrDefault(x, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (sH.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Main T = new Main();
System.out.println(T.solution("statitsics"));
}
}
import java.util.HashMap;
import java.util.Map;
public class Solution {
private static int solution(String s){
int[] frequency = new int[26];
char[] chars = s.toCharArray();
for(char c:chars) frequency[c-'a']++;
for(int i = 0; i < chars.length; i++)
if(frequency[chars[i]-'a'] == 1) return i;
return -1;
}
private static int solution2(String s){
Map<Character, Integer> countMap = new HashMap<>();
for (char c : s.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
int firstIndex = Integer.MAX_VALUE;
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
int index = s.indexOf(entry.getKey());
if (index < firstIndex) {
firstIndex = index;
}
}
}
return firstIndex == Integer.MAX_VALUE ? -1 : firstIndex;
}
public static void main(String[] args) {
System.out.println(solution("statitsics"));
System.out.println(solution("aabb"));
System.out.println(solution("stringshowtime"));
System.out.println(solution("abcdeabcdfg"));
System.out.println(solution("teachertimeachest"));
System.out.println(solution2("statitsics"));
System.out.println(solution2("aabb"));
System.out.println(solution2("stringshowtime"));
System.out.println(solution2("abcdeabcdfg"));
System.out.println(solution2("teachertimeachest"));
}
}
3. 풀이