1. Description
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so, the concatenation of the-words, i.e. is a palindrome.
Example 1:
Given words =["bat", "tab", "cat"]
Return[[0, 1], [1, 0]]
The palindromes is["battab", "tabbat"]
Example 2:
Given words =["abcd", "dcba", "lls", "s", "sssll"]
Return[[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes is["dcbaabcd", "abcddcba", "slls", "llssssll"]
2. Answer
Public classSolution { PublicList<list<integer>>palindromepairs (string[] words) {List<List<Integer>> res =NewArraylist<list<integer>>(); if(Words = =NULL|| Words.length = = 0){ returnRes; } //Build the Map Save the Key-val pairs:string-idxhashmap<string, integer> map =NewHashmap<>(); for(inti = 0; i < words.length; i++) {map.put (words[i], i); } //Special Cases: "" can be combine with any palindrome string if(Map.containskey ("")) { intBlankidx = Map.get (""); for(inti = 0; i < words.length; i++) { if(Ispalindrome (Words[i])) {if(i = =blankidx)Continue; Res.add (Arrays.aslist (Blankidx, i)); Res.add (Arrays.aslist (i, blankidx)); } } } //Find all string and reverse string pairs for(inti = 0; i < words.length; i++) {String Cur_r=reversestr (Words[i]); if(Map.containskey (Cur_r)) {intFound =Map.get (Cur_r); if(found = = i)Continue; Res.add (Arrays.aslist (i, found)); } } //find the pair s1, S2 that//Case1:s1[0:cut] is palindrome and s1[cut+1:] = reverse (s2) = (s2, s1)//case2:s1[cut+1:] is palindrome and s1[0:cut] = reverse (s2) = = (S1, s2) for(inti = 0; i < words.length; i++) {String cur=Words[i]; for(intCut = 1; Cut < Cur.length (); cut++) { if(Ispalindrome (cur.substring (0, cut))) {String Cut_r=Reversestr (cur.substring (cut)); if(Map.containskey (Cut_r)) {intFound =Map.get (Cut_r); if(found = = i)Continue; Res.add (arrays.aslist (found, i)); } } if(Ispalindrome (cur.substring (cut))) {String Cut_r= Reversestr (cur.substring (0, cut)); if(Map.containskey (Cut_r)) {intFound =Map.get (Cut_r); if(found = = i)Continue; Res.add (Arrays.aslist (i, found)); } } } } returnRes; } Publicstring Reversestr (String str) {StringBuilder SB=NewStringBuilder (str); returnsb.reverse (). toString (); } Public BooleanIspalindrome (String s) {inti = 0; intj = s.length ()-1; while(I <=j) { if(S.charat (i)! =S.charat (j)) { return false; } I++; J--; } return true; } }
"Leetcode" Palindrome Pairs (336)