-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_17.cpp
102 lines (81 loc) · 2.09 KB
/
code_17.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "code.h"
#include <vector>
#include "gtest/gtest.h"
#include <string>
using namespace std;
void call_code_17(){}
#define DEBUG
#ifdef DEBUG
#define OJDBG std::cout
#else
#define OJDBG 0 && std::cout
#endif
class Solution_17 {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty())
{
return m_result;
}
InitDict();
string joinchar;
JoinChar(digits, 0, joinchar);
return m_result;
}
void PrintResult()
{
OJDBG << "m_result = {";
for (auto str : m_result)
{
OJDBG << str << ", ";
}
OJDBG << "}" << endl;
}
private:
map<int, vector<char>> m_dict;
vector<string> m_result;
void InitDict()
{
m_dict['2'] = {'a','b','c'};
m_dict['3'] = {'d','e','f'};
m_dict['4'] = {'g','h','i'};
m_dict['5'] = {'j','k','l'};
m_dict['6'] = {'m','n','o'};
m_dict['7'] = {'p','q','r','s'};
m_dict['8'] = {'t','u','v'};
m_dict['9'] = {'w','x','y','z'};
}
void JoinChar(const string& digits, int pos, string joinchar)
{
if (pos >= digits.size())
{
OJDBG << "Error! pos = " << pos << " digits = " << digits << endl;
return;
}
char key = digits.at(pos);
auto charArray = m_dict[key];
for (auto ch : charArray)
{
if (pos < digits.size() - 1)
{
// 未到迭代末尾,继续拼接字母
JoinChar(digits, pos + 1, joinchar + ch);
}
else
{
// 到达迭代末尾,输出组合词
m_result.push_back(joinchar + ch);
}
}
}
};
TEST(Test_Code_17, test1)
{
string test = "23";
Solution_17 sln;
vector<string> result = {"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"};
auto output = sln.letterCombinations(test);
sln.PrintResult();
EXPECT_TRUE(output.size() == result.size());
EXPECT_TRUE(output == result);
}