-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmain.cpp
74 lines (64 loc) · 1.67 KB
/
main.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
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> result;
unordered_map<string, int> reversed;
for (int i = 0; i < words.size(); ++i) {
string t = words[i];
reverse(t.begin(), t.end());
reversed[t] = i;
}
for (int i = 0; i < words.size(); ++i) {
string w = words[i];
int len = w.size();
if (reversed.count(w) && reversed[w] != i) {
result.push_back({i, reversed[w]});
}
for (int d = 0; d < len; d++) {
string right_half = w.substr(len - d);
if (isPalindrome(w, 0, len - d - 1) && reversed.count(right_half)) {
result.push_back({reversed[right_half], i});
}
string left_half = w.substr(0, d);
if (isPalindrome(w, d, len - 1) && reversed.count(left_half)) {
result.push_back({i, reversed[left_half]});
}
}
}
return result;
}
bool isPalindrome(string t, int left, int right) {
while (left < right) {
if (t[left++] != t[right--]) {
return false;
}
}
return true;
}
};
int main() {
Solution sol;
vector<string> words;
words = {"bat", "tab", "cat"};
for (auto &v: sol.palindromePairs(words)) {
cout << v[0] << "," << v[1] << endl;
}
words = {"abcd", "dcba", "lls", "s", "sssll"};
for (auto &v: sol.palindromePairs(words)) {
cout << v[0] << "," << v[1] << endl;
}
return 0;
}