Leetcode

First Unique Character in a String

  • Time:O(n)
  • Space:O(128) = O(1)

C++

class Solution {
 public:
  int firstUniqChar(string s) {
    vector<int> count(128);

    for (const char c : s)
      ++count[c];

    for (int i = 0; i < s.length(); ++i)
      if (count[s[i]] == 1)
        return i;

    return -1;
  }
};

JAVA

class Solution {
  public int firstUniqChar(String s) {
    int[] count = new int[128];

    for (final char c : s.toCharArray())
      ++count[c];

    for (int i = 0; i < s.length(); ++i)
      if (count[s.charAt(i)] == 1)
        return i;

    return -1;
  }
}

Python

class Solution:
  def firstUniqChar(self, s: str) -> int:
    count = Counter(s)

    for i, c in enumerate(s):
      if count[c] == 1:
        return i

    return -1