Simple Java Solution


  • 0
    public int firstUniqChar(String s) {
            int[] table = new int[256];
            for(int i = 0; i < s.length(); i++){
                ++table[s.charAt(i)];
            }
            for(int i = 0; i < s.length(); i++){
                if(table[s.charAt(i)] == 1){
                    return i;
                }
            }
            return -1;
        } 
        // Or
        public int firstUniqChar(String s) {
            int[] table = new int[26];
            for(int i = 0; i < s.length(); i++){
                ++table[s.charAt(i) - 97];
            }
            for(int i = 0; i < s.length(); i++){
                if(table[s.charAt(i) - 97] == 1){
                    return i;
                }
            }
            return -1;
        } 
    
    // Or :
    
    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                return i;
            }
        }
        return -1;
    }
    

Log in to reply
 

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