Advertisement
SalmaYasser

Untitled

Jan 19th, 2020
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. Assumption: No duplicated string in the given dictionary
  2.  
  3. Steps:
  4.  
  5. Traverse the array, build map. Key is the reversed string, value is index in array (0 based)
  6.  
  7. Edge case - check if empty string exists. It's interesting that for given words {"a", ""}, it's expected to return two results [0,1] and [1,0]. Since my main logic can cover [0, 1] concatenate("a", ""), so as to cover the other situation concatenate("", "a"), I need to traverse the words array again, find the palindrome word candidate except "" itself, and add pair("", palindrome word) to the final answer.
  8.  
  9. Main logic part. Partition the word into left and right, and see 1) if there exists a candidate in map equals the left side of current word, and right side of current word is palindrome, so concatenate(current word, candidate) forms a pair: left | right | candidate. 2) same for checking the right side of current word: candidate | left | right.
  10.  
  11. class Solution {
  12. public:
  13. vector<vector<int>> palindromePairs(vector<string>& words) {
  14. unordered_map<string, int> dict;
  15. vector<vector<int>> ans;
  16. // build dictionary
  17. for(int i = 0; i < words.size(); i++) {
  18. string key = words[i];
  19. reverse(key.begin(), key.end());
  20. dict[key] = i;
  21. }
  22. // edge case: if empty string "" exists, find all palindromes to become pairs ("", self)
  23. if(dict.find("")!=dict.end()){
  24. for(int i = 0; i < words.size(); i++){
  25. if(i == dict[""]) continue;
  26. if(isPalindrome(words[i])) ans.push_back({dict[""], i}); // 1) if self is palindrome, here ans covers concatenate("", self)
  27. }
  28. }
  29.  
  30. for(int i = 0; i < words.size(); i++) {
  31. for(int j = 0; j < words[i].size(); j++) {
  32. string left = words[i].substr(0, j);
  33. string right = words[i].substr(j, words[i].size() - j);
  34.  
  35. if(dict.find(left) != dict.end() && isPalindrome(right) && dict[left] != i) {
  36. ans.push_back({i, dict[left]}); // 2) when j = 0, left = "", right = self, so here covers concatenate(self, "")
  37. }
  38.  
  39. if(dict.find(right) != dict.end() && isPalindrome(left) && dict[right] != i) {
  40. ans.push_back({dict[right], i});
  41. }
  42. }
  43. }
  44.  
  45. return ans;
  46. }
  47.  
  48. bool isPalindrome(string str){
  49. int i = 0;
  50. int j = str.size() - 1;
  51.  
  52. while(i < j) {
  53. if(str[i++] != str[j--]) return false;
  54. }
  55.  
  56. return true;
  57. }
  58.  
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement