Java solution - O(n)


  • 0
    G

    Time complexity: O(n). Travel the string array index.
    Space complexity: O(n). create the charTable: char[128].

    class Solution {
        public int firstUniqChar(String s) {
                   char[] charTable = new char[128];
    		
    		for(int i = 0 ; i < s.length() ; i++){
    			charTable[s.charAt(i)]++; 
    		}
    
    		for(int i = 0 ; i < s.length() ; i++){
    			if(charTable[s.charAt(i)] == 1){
    				return i;
    			}
    		}	
    		return -1;  
        }
    }
    

Log in to reply
 

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