#include <vector>
#include <string>
#include <iostream>
#include <unordered_map>
using namespace std;
/*
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list.
So that the concatenation of two words. ie, words[i] + words[j] is a palindrome.
Example:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
*/
bool isPalindrome(string s) {
if(s.size() <= 1) return true;
int i = 0;
int j = s.size()-1;
while(i <= j) {
if(s[i] != s[j]) return false;
i++;
j--;
}
return true;
}
// Time complexity O(N^2).... too high....
vector< vector<int> > palindromePairs(vector<string>& words) {
vector< vector<int> > res;
unordered_map<string, int> stringToIndex;
for(int i = 0; i < words.size(); ++i) {
stringToIndex.insert({words[i], i});
}
for(int i = 0; i < words.size(); ++i) {
auto iter = stringToIndex.begin();
while(iter != stringToIndex.end()) {
vector<int> tmp;
if(iter->first == words[i]) {iter++; continue;}
if(isPalindrome(iter->first + words[i])) {
tmp.push_back(iter->second);
tmp.push_back(i);
res.push_back(tmp);
}
iter++;
}
}
return res;
}
bool isPalindrome(string s, int start, int end) {
if(start > end) return false;
while(start <= end) {
if(s[start] == s[end]) {start++; end--; continue;}
return false;
}
return true;
}
// Get the idea from LeetCode forum. Time Complexity O(NK), Space O(N), it currently wont run.....;(
vector< vector<int> > palindromePairsII(vector<string>& words) {
unordered_map<string, int> hashMap;
vector< vector<int> > res;
for(int i = 0; i < words.size(); ++i) {
hashMap.insert({words[i], i});
}
for(int i = 0; i < words.size(); ++i) {
string curr = words[i];
int n = curr.size();
for(int l = 0; l < n; ++i) {
if(isPalindrome(curr, 0 , l - 1)) {
string tmp = curr.substr(l);
if(hashMap.count(tmp)) {
int k = hashMap[tmp];
if(i != k) res.push_back(vector<int>{i, k});
}
}
if(isPalindrome(curr, l, n - 1)) {
string tmp = curr.substr(0, n-l);
if(hashMap.count(tmp)) {
int k = hashMap[tmp];
if(i != k) res.push_back(vector<int>{i, k});
}
}
}
}
return res;
}
int main(void) {
vector<string> words{"abcd", "dcba", "lls", "s", "sssll"};
vector< vector<int> > res = palindromePairs(words);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << " ";
}
cout << endl;
}
}
LeetCode 336. Palindrome Pairs
最新推荐文章于 2021-03-01 12:01:26 发布