From 4830210f692894edbb851c0c51e4c732b9143fff Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Sat, 4 Feb 2023 16:51:01 +0400 Subject: [PATCH] add leetcode Verifying an Alien Dictionary (#1205) * add leetcode Verifying an Alien Dictionary * updating DIRECTORY.md * Update 953.c add blank line at the end --------- Co-authored-by: github-actions[bot] Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/953.c | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 leetcode/src/953.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 7e76feed..8e0d621b 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -110,6 +110,7 @@ | 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters) | [C](./src/917.c) | Easy | | 931 | [Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum) | [C](./src/931.c) | Medium | | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst) | [C](./src/938.c) | Easy | +| 953 | [Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary) | [C](./src/953.c) | Easy | | 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree) | [C](./src/965.c) | Easy | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) | [C](./src/977.c) | Easy | | 979 | [Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree) | [C](./src/979.c) | Medium | diff --git a/leetcode/src/953.c b/leetcode/src/953.c new file mode 100644 index 00000000..cb13d85d --- /dev/null +++ b/leetcode/src/953.c @@ -0,0 +1,40 @@ +#define min(x, y) (((x) < (y)) ? (x) : (y)) + +bool isWordLess(char* word1, char* word2, int* charOrder){ + int word1Length = strlen(word1); + int word2Length = strlen(word2); + + for(int i = 0; i < min(word1Length, word2Length); i++) { + int charWordsDiff = (charOrder[word1[i] - 'a'] - charOrder[word2[i] - 'a']); + + if (charWordsDiff < 0){ + return true; + } + + if (charWordsDiff > 0){ + return false; + } + } + + return word1Length <= word2Length; +} + +// Keep array-hashtable of order letters. +// Runtime: O(n) +// Space: O(1) +bool isAlienSorted(char ** words, int wordsSize, char * order){ + const int lowerCaseLettersNumber = 26; + int charorder[lowerCaseLettersNumber]; + + for(int i = 0; i < lowerCaseLettersNumber; i++) { + charorder[order[i] - 'a'] = i; + } + + for(int i = 0; i < wordsSize - 1; i++) { + if (!isWordLess(words[i], words[i + 1], charorder)){ + return false; + } + } + + return true; +}