Eric interview Question 1

Run Settings
LanguageC++
Language Version
Run Command
// To execute C++, please define "int main()" #include <iostream> #include <string> #include <algorithm> #include <vector> #include <map> using namespace std; bool isAna (string &a, string& b){ if (a.size() != b.size()) return false; sort (a.begin(), a.end()); sort (b.begin(), b.end()); for (int i = 0; i < a.size(); i ++){ if (a[i] != b[i]) return false; } return true; } vector<vector<string>> getAnaWords(vector<string> words){ vector<vector<string>> anaResult; vector<string>::iterator i_it = words.begin(); while (i_it != words.end()) { vector<string> tmp; vector<string>::iterator j_it = words.begin()+1; while (j_it != words.end()) { if (isAna(*i_it, *j_it)) { tmp.push_back(*j_it); j_it = words.erase(j_it); } else { j_it++; } } tmp.push_back(*i_it); i_it = words.erase(i_it); anaResult.push_back(tmp); } return anaResult; } void printAnaWords(vector<vector<string>> anaStore){ for (int i = 0; i < anaStore.size(); i ++){ cout << "{"; for (auto elem: anaStore[i]){ cout << elem << ", "; } cout << "}"; cout <<" ++ "; }cout <<endl; } int main() { vector<string> str= {"dog", "god", "happy", "appyh", "abcdefg","gfedcba"}; vector<vector<string>> anaStore = getAnaWords(str); printAnaWords(anaStore); // {{"dog", "god"},{"happy", "appyh"}, {"abcdefg", "gfedcba"}}; } /* Your previous Python 2 content is preserved below: ''' anagram - a word, phrase, or name formed by rearranging the letters of another, ex: cinema and iceman anagram_buckets - return a collection of words grouped together if they are anagrams of each other ex: words = ['dog', 'hello', 'rats', 'arts', 'god', 'star'] anagram_buckets(words) -> [['dog', 'god'], ['hello', 'lleho'], ['rats', 'arts', 'star']] ''' import collections def anagram_buckets(words): d = collections.defaultdict(lambda : []) for word in words: d["".join(sorted(word))].append(word) return d.values() if __name__ == "__main__": words = ['dog', 'hello', 'lleho', 'rats', 'arts', 'god', 'star', 'asdf'] print words print anagram_buckets(words) */
Editor Settings
Theme
Key bindings
Full width
Lines