[LeetCode] Find Resultant Array After Removing Anagrams

2273. Find Resultant Array After Removing Anagrams

You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.

In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.

Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, “dacb” is an anagram of “abdc”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
bool anagram(string& a, string& b) {
if(a.length() != b.length()) return false;
unordered_map<char, int> counter;
for(auto& ch : a)
counter[ch]++;
for(auto& ch : b)
counter[ch]--;
for(auto& [_, c] : counter)
if(c) return false;
return true;
}
public:
vector<string> removeAnagrams(vector<string>& words) {
vector<string> st;
for(auto& w : words) {
if(st.empty() or !anagram(st.back(), w)) {
st.push_back(w);
}
}

return st;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/LeetCode/find-resultant-array-after-removing-anagrams/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.