notes/CS notes/pages/Leetcode First-Unique-Character-In-a-String.md
2022-06-14 23:34:11 +08:00

1.4 KiB

Leetcode First-Unique-Character-In-a-String

2022-06-14 13:10


Algorithms:

#algorithm

Data structures:

#DS #string #array #hash_table

Difficulty:

#leetcode #coding_problem #difficulty-easy

tag:#string OR tag:#hash_table

Problem

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

Examples

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.

Thoughts

Really, really simple hash map problem. Shouldn't have taken so much time.

[!summary] Don't overlook simple problems! #tip

Solution

class Solution {
public:
    int firstUniqChar(string s) {
      // O(1) hashmap
      int umap[26] = {};
      
      int sSize = s.size();
      for (int i = 0; i < sSize; i++) {
          umap[s[i] - 'a']++;
      }
      
      for (int i = 0; i < sSize; i++) {
        if (umap[s[i] - 'a'] == 1) {
          return i;
        }
      }
      return -1;
    }
};