39ms Java O(n) Solution - Hash Table, Easy to Understand


  • 0

    Use an array to serve as hash table, record the position and character appearance time. And then traverse the hash table to find the smallest position.

    public class Solution {
        public int firstUniqChar(String s) {
            Ele[] hash = new Ele[26];
            for(int i = 0; i < s.length(); i++){
                if(hash[s.charAt(i) - 'a'] == null){
                    Ele tmp = new Ele(i,1);
                    hash[s.charAt(i) - 'a'] = tmp;
                }else{
                    hash[s.charAt(i) - 'a'].value++;
                }
            }
            int res = Integer.MAX_VALUE;
            for(int i = 0; i < 26; i++){
                if(hash[i] != null && hash[i].value == 1){
                    if(hash[i].pos < res) res = hash[i].pos;
                }
            }
            if(res == Integer.MAX_VALUE) res = -1;
            return res;
        }
    }
    class Ele{
        int pos, value;
        public Ele(int pos, int value){
            this.pos = pos;
            this.value = value;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.