Skip to content

387. First Unique Character in a String 👍

  • Time: $O(n)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
  }
}
1
2
3
4
5
6
7
8
9
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
Back to top