Post

First Unique Character in a String

LeetCode https://leetcode.cn/problems/first-unique-character-in-a-string/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int firstUniqChar(String s) {

        HashMap<Character, Integer> map = new HashMap<>();
        for (char ch : s.toCharArray()) {
            map.put(ch, map.getOrDefault(ch, 0) + 1);            
        }
        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;
    }
}

Optimize

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int firstUniqChar(String s) {

        int min = Integer.MAX_VALUE;
        for (char c = 'a'; c <= 'z'; ++c){
            int index = s.indexOf(c);
            if (index != -1 &&  index == s.lastIndexOf(c))
                min = Math.min(min, index);
        }
        
        return min == Integer.MAX_VALUE ? -1: min;
    }
}
This post is licensed under CC BY 4.0 by the author.