I'm posting my C++ code for LeetCode's Expressive Words. If you have time and would like to review, please do so. Thank you!
Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.
For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S.
Given a list of query words, return the number of words that are stretchy.
Example: Input: S = "heeellooo" words = ["hello", "hi", "helo"]
Output: 1 Explanation: We can extend "e" and "o" in the word "hello"
to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.Notes:
0 <= len(S) <= 100.
0 <= len(words) <= 100.
0 <= len(words[i]) <= 100. S and all words in words consist only of lowercase letters
Accepted C++
class Solution { public: int expressiveWords(std::string base_string, std::vector<string> &words) { int count = 0; for (auto &word : words) if (is_stretchable(base_string, word)) count++; return count; } protected: bool is_stretchable(std::string base_string, std::string words) { // 4 pointers int base_length = base_string.size(); int words_length = words.size(); int left_a = 0, right_a = 0; for (int left_b = 0, right_b = 0; left_a < base_length && right_a < words_length; left_a = left_b, right_a = right_b) { if (base_string[left_a] != words[right_a]) return false; while (left_b < base_length && base_string[left_b] == base_string[left_a]) left_b++; while (right_b < words_length && words[right_b] == words[right_a]) right_b++; if (left_b - left_a != right_b - right_a && left_b - left_a < std::max(3, right_b - right_a)) return false; } return left_a == base_length && right_a == words_length; } };
Reference
On LeetCode, there is an instance usually named Solution
with one or more public
functions which we are not allowed to rename those.