forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decrypt-string-from-alphabet-to-integer-mapping.cpp
77 lines (71 loc) · 1.74 KB
/
decrypt-string-from-alphabet-to-integer-mapping.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
// Time: O(n)
// Space: O(1)
// forward solution
class Solution {
public:
string freqAlphabets(string s) {
string result;
int i = 0;
while (i < s.length()) {
if (i + 2 < s.length() && s[i + 2] == '#') {
result.push_back(alpha(s.substr(i, 2)));
i += 3;
} else {
result.push_back(alpha(s.substr(i, 1)));
++i;
}
}
return result;
}
private:
char alpha(const string& s) {
return 'a' + stoi(s) - 1;
}
};
// Time: O(n)
// Space: O(1)
// backward solution
class Solution2 {
public:
string freqAlphabets(string s) {
string result;
int i = s.length() - 1;
while (i >= 0) {
if (s[i] == '#') {
result.push_back(alpha(s.substr(i - 2, 2)));
i -= 3;
} else {
result.push_back(alpha(s.substr(i, 1)));
--i;
}
}
reverse(result.begin(), result.end());
return result;
}
private:
char alpha(const string& s) {
return 'a' + stoi(s) - 1;
}
};
// Time: O(n)
// Space: O(1)
// regex solution
class Solution3 {
public:
string freqAlphabets(string s) {
string result;
int submatches[] = { 1, 2 };
const auto e = regex("(\\d\\d#)|(\\d)");
for (regex_token_iterator<string::const_iterator> it(s.cbegin(), s.cend(), e, submatches), end;
it != end;) {
const auto& a = (it++)->str();
const auto& b = (it++)->str();
result.push_back(alpha(!a.empty() ? a : b));
}
return result;
}
private:
char alpha(const string& s) {
return 'a' + stoi(s) - 1;
}
};