aboutsummaryrefslogtreecommitdiff
path: root/find_replace_pattern.c
blob: 64dc0152adc4c7d07f295734780d075edb7456dd (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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

bool check(char *word, char *lookup, char *q) {
  memset(lookup, -1, 26);
  for (int i = 0; word[i] != '\0'; ++i) {
    if (lookup[word[i] - 'a'] == -1)
      lookup[word[i] - 'a'] = i;
    if (q[i] != lookup[word[i] - 'a'])
      return false;
  }
  return true;
}

// note the returned array must be malloc'd (assume caller free()'s)

char **findAndReplacePattern(char **words, int wordsSize, char *pattern,
                             int *returnSize) {
  char lookup[26];
  memset(lookup, -1, 26);
  char q[50] = {0};
  char **ans = malloc(sizeof(char **) * wordsSize);
  size_t len = strlen(pattern);
  for (int i = 0; i < len; ++i) {
    if (lookup[pattern[i] - 'a'] == -1)
      lookup[pattern[i] - 'a'] = i;
    q[i] = lookup[pattern[i] - 'a'];
  }
  int sz = 0;
  for (int i = 0; i < wordsSize; ++i) {
    if (check(words[i], lookup, q)) {
      char *k = malloc(sizeof(char) * (len + 1));
      memcpy(k, words[i], len + 1);
      ans[sz++] = k;
    }
  }
  *returnSize = sz;
  return ans;
}

int main() {
  char *words1[] = {"abc", "deq", "mee", "aqq", "dkd", "ccc"},
       *words2[] = {"a", "b", "c"};
  char pattern1[] = {"abb"}, pattern2[] = {"a"};
}