Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/387.html

 387	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.

 Examples:

 s = "leetcode"
 return 0.

 s = "loveleetcode",
 return 2.

 Note: You may assume the string contain only lowercase letters.

Algorithm

The hash table builds a mapping between each character and its number of occurrences, and then traverses the string in order, finds the first character with a number of occurrences of 1, and returns its position.

Code

  • 
    public class First_Unique_Character_in_a_String {
    
        public static void main (String[] args) {
            First_Unique_Character_in_a_String out = new First_Unique_Character_in_a_String();
            Solution s = out.new Solution();
    
            System.out.println(s.firstUniqChar("loveleetcode"));
        }
    
        class Solution {
            public int firstUniqChar(String s) {
    
                if (s == null || s.length() == 0) {
                    return -1;
                }
    
                // unique[i] meaning index i has no duplicate
                int[] count = new int[256];
    
                for (char each: s.toCharArray()) {
                    count[each] += 1;
                }
    
                for (int i = 0; i < s.length(); i++) {
                    if (count[s.charAt(i)] == 1) {
                        return i;
                    }
                }
    
                return -1;
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/first-unique-character-in-a-string/
    // Time: O(S)
    // Space: O(1)
    class Solution {
    public:
        int firstUniqChar(string s) {
            int cnt[26] = {0};
            for (char c : s) cnt[c - 'a']++;
            for (int i = 0; i < s.size(); ++i) {
                if (cnt[s[i] - 'a'] == 1) return i;
            }
            return -1;
        }
    };
    
  • class Solution:
        def firstUniqChar(self, s: str) -> int:
            counter = Counter(s)
            for i, c in enumerate(s):
                if counter[c] == 1:
                    return i
            return -1
    
    ############
    
    class Solution(object):
      def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters = [0] * 26
        for c in s:
          ci = ord(c) - ord('a')
          letters[ci] += 1
        for i in range(0, len(s)):
          ci = ord(s[i]) - ord('a')
          if letters[ci] == 1:
            return i
        return -1
    
    

All Problems

All Solutions