First Unique Character in a String

By | September 1, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 387

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.

Solution. From g4g. During the first time scan,
1. Count the frequency of each char.
2. Store the position of each char where it is firstly visited
In the second time, just scan the 26 times to find the lowest position iwhere the count is 1.

public int firstUniqChar(String s) {
    int[] firstTime = new int[26], count = new int[26];
    for (int i = 0; i < s.length(); i++) {  // one time loop save the count of each char, and position of first visit.
        char ch = s.charAt(i);
        if (++count[ch - 'a'] == 1) {
            firstTime[ch - 'a'] = i;
        }
    }
    int ans = -1;
    for (int i = 0; i < firstTime.length; i++) {    // for elements which only show 1 time, get the smallest position.
        if (count[i] == 1 && firstTime[i] < ans) {
            ans = firstTime[i];
        }
    }
    return ans;
}

Check my code on github.