Wednesday, August 24, 2016

387. First Unique Character in a String

This is very similar to the second question I was asked in an Amazon interview back to 2014. Here's my solution for it.
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public int firstUniqChar(String s) {
        if(s==null ||s.length()==0)return -1;
        if(s.length()==1)return 0;
        
        int[] positions = new int[26];
        for(int i=0;i<26;i++){
            positions[i]=Integer.MIN_VALUE;
        }
        //set repeated ones with -1
        for(int i=0;i<s.length();i++){
            int curCharIndex = s.charAt(i)-'a';
            if(positions[curCharIndex]==Integer.MIN_VALUE){
                positions[curCharIndex]=i;
            }else if(positions[curCharIndex]>=0){
                positions[curCharIndex]=-1;
            }
        }
        for(int i=0;i<s.length();i++){
            int curCharIndex = s.charAt(i)-'a';
            if(positions[curCharIndex]>=0){
                return positions[curCharIndex];
            }
        }
        return -1;
    }
}

No comments: