aboutsummaryrefslogtreecommitdiff
path: root/find_replace_pattern.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /find_replace_pattern.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'find_replace_pattern.c')
-rw-r--r--find_replace_pattern.c48
1 files changed, 48 insertions, 0 deletions
diff --git a/find_replace_pattern.c b/find_replace_pattern.c
new file mode 100644
index 0000000..64dc015
--- /dev/null
+++ b/find_replace_pattern.c
@@ -0,0 +1,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"};
+}