Skip to content

Commit c3f4709

Browse files
committed
palindrome_pairs
1 parent be9ad01 commit c3f4709

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
240240
#### [332. Reconstruct Itinerary](https://github.com/hitzzc/go-leetcode/tree/master/reconstruct_ltinerary)
241241
#### [334. Increasing Triplet Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/increasing_triplet_subsequence)
242242
#### [335. Self Crossing](https://github.com/hitzzc/go-leetcode/tree/master/self_crossing)
243+
#### [336. Palindrome Pairs](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_pairs)
243244

244245

245246

palindrome_pairs/palindrome_pairs.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> palindromePairs(vector<string>& words) {
4+
vector<vector<int>> results;
5+
unordered_map<string, int> mapping;
6+
set<int> index_set;
7+
for (int i = 0; i < words.size(); ++i) {
8+
mapping[words[i]] = i;
9+
index_set.insert(words[i].size());
10+
}
11+
for (int i = 0; i < words.size(); ++i) {
12+
string word = words[i];
13+
int len = word.size();
14+
reverse(word.begin(), word.end());
15+
if (mapping.count(word) != 0 && mapping[word] != i) {
16+
results.push_back(vector<int>{i, mapping[word]});
17+
}
18+
for (auto j = index_set.begin(); j != index_set.find(word.size()); ++j) {
19+
int d = *j;
20+
if (is_palindrome(word, 0, len - d - 1) && mapping.count(word.substr(len - d))) {
21+
results.push_back({i, mapping[word.substr(len - d)]});
22+
}
23+
if (is_palindrome(word, d, len - 1) && mapping.count(word.substr(0, d))) {
24+
results.push_back({mapping[word.substr(0, d)], i});
25+
}
26+
}
27+
}
28+
return results;
29+
}
30+
31+
bool is_palindrome(string& s, int i, int j) {
32+
while (i < j) {
33+
if (s[i++] != s[j--]) return false;
34+
}
35+
return true;
36+
}
37+
};

0 commit comments

Comments
 (0)