Easy to Understand 20ms Java Solution


  • 0
    E

    countAndIndex[0][] is the times every character appears,
    countAndIndex[1][] is the index of it.

    public class Solution {
        public int firstUniqChar(String s) {
            int len = s.length();
            int result = Integer.MAX_VALUE;
            if(len == 0){
            	return -1;
            }
            if(len == 1){
            	return 0;
            }
        	int [][] countAndIndex = new int[2][26];
        	for(int i=0;i<26;i++){
        		countAndIndex[0][i] = 0;
        	}
            char [] str = s.toCharArray();
            
            for(int i=0;i<len;i++){
            	countAndIndex[0][str[i]-'a']++;
            	countAndIndex[1][str[i]-'a'] = i;
            }
            
            for(int i=0;i<26;i++){
            	if(countAndIndex[0][i] == 1 && result>countAndIndex[1][i]){
            	    result = countAndIndex[1][i];
            	}
            }
            
            return result == Integer.MAX_VALUE?-1:result;
        }
    }
    

Log in to reply
 

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