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;
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ