[AlgoExpert] Phone Number Mnemonics

Phone Number Mnemonics

  • Time : O(n * 4^n)
  • Space : O(n * 4^n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <vector>
using namespace std;

vector<string> phoneNumberMnemonics(string phoneNumber) {
unordered_map<char, vector<char>> mp{
{'1',{'1'}},
{'2',{'a','b','c'}},
{'3',{'d','e','f'}},
{'4',{'g','h','i'}},
{'5',{'j','k','l'}},
{'6',{'m','n','o'}},
{'7',{'p','q','r','s'}},
{'8',{'t','u','v'}},
{'9',{'w','x','y','z'}},
{'0',{'0'}}
};
vector<string> res;
res.push_back("");
for(auto& ch : phoneNumber) {
vector<string> tmp;
for(auto& build : res) {
for(auto& pad : mp[ch]) {
tmp.push_back(build + string(1,pad));
}
}

swap(res, tmp);
}

return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/14/PS/AlgoExpert/phone-number-mnemonic/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.