Java O(n) 16ms solution


  • 0
    B

    toCharArray's run time is much faster then string.charAt : )
    just simply store the letters of s into a index array int[] arrInt and then do a one pass search of the arrChar to find the first letter only appears once, i.e. the arrInt[i] == 1;

    class Solution {
        public int firstUniqChar(String s) {
            if(s.length() == 0) return -1;
            int res = 0;
            char[] arrChar = s.toCharArray();
            int[] arrInt = new int[256];
            for(char c : arrChar){
                arrInt[(int)c]++;
            }
            for(int i = 0; i < arrChar.length; i++){
                if(arrInt[(int)arrChar[i]] == 1){
                    res = i;
                    break;
                }else{res = -1;}
            }
            return res;
        }
    }
    

Log in to reply
 

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