aboutsummaryrefslogtreecommitdiff
path: root/first_unique_char_string.c
blob: 27ae3a7bd32c921822f302e468ccc877add69c73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 387. First Unique Character in a String
#include "leetcode.h"

/*
 * given a string 's', find the first non-repeating character in it and return
 * its index. if it does not exist, return -1
 */

int firstUniqChar(char *s) {
  int cnt[26], n = strlen(s);
  memset(cnt, 0, sizeof(int) * 26);
  for (int i = 0; i < n; i++) {
    char c = s[i];
    cnt[c - 'a'] += 1;
  }
  for (int i = 0; i < n; i++) {
    char c = s[i];
    if (cnt[c - 'a'] == 1)
      return i;
  }
  return -1;
}

int main() {
  char *s1 = "leetcode", *s2 = "loveleetcode", *s3 = "aabb";
  printf("%d\n", firstUniqChar(s1)); // expect: 0
  printf("%d\n", firstUniqChar(s2)); // expect: 2
  printf("%d\n", firstUniqChar(s3)); // expect: -1
}