[Coding Test] JAVA 한 번 사용한 최초문자 - HashMap

LeeSeungEun·2023년 5월 11일
0

Coding Test

목록 보기
7/38

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);
        }  //  Result : {a=1, s=3, c=1, t=3, i=2}
        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")); // 2
    }
}
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. 풀이

0개의 댓글