Algorithm


Problem Name: 387. First Unique Character in a String

Problem Link: https://leetcode.com/problems/first-unique-character-in-a-string/
 

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Code Examples

#1 Code Example with C Programming

Code - C Programming


int firstUniqChar(char* s) {
    int num[26] = { 0 };
    int idx[26];
    int i, j;
    
    i = 0;
    while (s[i]) {
        num[s[i] - 'a'] ++;
        idx[s[i] - 'a'] = i;
        i ++;
    }
    j = -1;
    for (i = 0; i  <  26; i ++) {
        if (num[i] == 1 && (j == -1 || j > idx[i])) {
            j = idx[i];
        }
    }
    return j;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "leetcode"

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int firstUniqChar(String s) {
    int[] count = new int[26];
    for (char c : s.toCharArray()) {
      count[c - 'a']++;
    }
    for (int i = 0; i  <  s.length(); i++) {
      if (count[s.charAt(i) - 'a'] == 1) {
        return i;
      }
    }
    return -1;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "leetcode"

#3 Code Example with Javascript Programming

Code - Javascript Programming


const firstUniqChar = function(s) {
  const arr = [];
  const res = [];
  const hash = {};
  let tmp;
  let idx;
  for (let i = 0; i  <  s.length; i++) {
    tmp = s.charAt(i);
    if (hash.hasOwnProperty(tmp)) {
      idx = arr.indexOf(tmp);
      if (idx >= 0) {
        arr.splice(idx, 1);
        res.splice(idx, 1);
      }

      hash[tmp] += 1;
    } else {
      arr.push(tmp);
      res.push(i);
      hash[tmp] = 1;
    }
  }
  return res[0] == null ? -1 : res[0];
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "loveleetcode"

Output

x
+
cmd
2

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = collections.defaultdict(int)
        for c in s:
            dic[c] += 1
        for i, c in enumerate(s):
            if dic[c] == 1: return i
        return -1
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "loveleetcode"

Output

x
+
cmd
2
Advertisements

Demonstration


Previous
#386 Leetcode Lexicographical Numbers Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#388 Leetcode Longest Absolute File Path Solution in C, C++, Java, JavaScript, Python, C# Leetcode