First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
  • Note:
You may assume the string contain only lowercase letters.
  • Examples:
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
  • Analysis:
First, use a map to counts the number of every character.

Second, loop the input string to find the first unique character.
  • Code - Java:
public class Solution {
    public int firstUniqChar(String s) {
        int len = s.length();
        int[] counts = new int[26];
        for (int i = 0; i < len; i++) {
            counts[s.charAt(i) - 'a'] += 1;
        }
        for (int i = 0; i < len; i++) {
            if (counts[s.charAt(i) - 'a'] == 1) {
                return i;
            } 
        }
        return -1;
    }
}
  • Code - C++:
class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> counts(26, 0);
        int len = s.length();
        for (int i = 0; i < len; i++) {
            counts[s[i] - 'a'] += 1;
        }
        for (int i = 0; i < len; i++) {
            if (counts[s[i] - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
};
  • Code - Python:
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        counts = [0 for i in range(26)]
        sLen = len(s)
        for ch in s:
            counts[ord(ch) - ord('a')] += 1
        for i in range(sLen):
            if counts[ord(s[i]) - ord('a')] == 1:
                return i
        return -1;
  • Time Complexity: O(N), N is the length of string

  • Space Complexity: O(N), N is the length of string

results matching ""

    No results matching ""