-
Notifications
You must be signed in to change notification settings - Fork 0
/
336. Palindrome Pairs.cpp
33 lines (31 loc) · 1.12 KB
/
336. Palindrome Pairs.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
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>>res;
buildTrie(words);
for(int i = 0; i < words.size(); i++){
string s = words[i];
for(auto x: Trie[s]) if(isPalindrome(x.first) && i != x.second) res.push_back({i, x.second});
for(int j = 0; j <= s.size(); j++)
if(m.count(s.substr(0, j)) && isPalindrome(s.substr(j)) && i != m[s.substr(0, j)])
res.push_back({i, m[s.substr(0, j)]});
}
return res;
}
private:
unordered_map<string, vector<pair<string, int> > >Trie;
unordered_map<string, int>m;
void buildTrie(vector<string>& words){
for(int i = 0; i < words.size(); i++){
string s = words[i];
reverse(s.begin(), s.end());
m[s] = i;
for(int j = 0; j < s.size(); j++) Trie[s.substr(0, j)].push_back({s.substr(j), i});
}
}
bool isPalindrome(string s){
int i = 0, j = s.size() - 1;
while(i < j) if(s[i++] != s[j--]) return false;
return true;
}
};