Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. /*
  2. time complexity O(m * n ^ 2) where m is the length of the list and the n is the length of the word.
  3.  
  4. There are several cases to be considered that isPalindrome(s1 + s2):
  5.  
  6. Case1: If s1 is a blank string, then for any string that is palindrome s2, s1+s2 and s2+s1 are palindrome.
  7.  
  8. Case 2: If s2 is the reversing string of s1, then s1+s2 and s2+s1 are palindrome.
  9.  
  10. Case 3: If s1[0:cut] is palindrome and there exists s2 is the reversing string of s1[cut+1:] , then s2+s1 is palindrome.
  11.  
  12. Case 4: Similiar to case3. If s1[cut+1: ] is palindrome and there exists s2 is the reversing string of s1[0:cut] ,
  13. then s1+s2 is palindrome.
  14. */
  15.  
  16. public class Solution {
  17. public List<List<Integer>> palindromePairs(String[] words) {
  18. List<List<Integer>> result = new ArrayList<List<Integer>>();
  19. if(words == null || words.length < 2) return result;
  20. HashMap<String, Integer> map = new HashMap<String, Integer>();
  21. for(int i=0; i<words.length; i++) map.put(words[i], i);
  22. for(int i=0; i<words.length; i++) {
  23. for(int j=0; j<=words[i].length(); j++) {
  24. String str1 = words[i].substring(0, j);
  25. String str2 = words[i].substring(j);
  26. if(isPalindrome(str1)) {
  27. String str2reverse = new StringBuilder(str2).reverse().toString();
  28. if(map.containsKey(str2reverse) && map.get(str2reverse) != i) {
  29. List<Integer> list = new ArrayList<Integer>();
  30. list.add(map.get(str2reverse));
  31. list.add(i);
  32. result.add(list);
  33. }
  34. }
  35. if(isPalindrome(str2)) {
  36. String str1reverse = new StringBuilder(str1).reverse().toString();
  37. // put str2.length()!=0 to avoid duplicates
  38. if(map.containsKey(str1reverse) && map.get(str1reverse) != i && str2.length() != 0) {
  39. List<Integer> list = new ArrayList<Integer>();
  40. list.add(i);
  41. list.add(map.get(str1reverse));
  42. result.add(list);
  43. }
  44. }
  45. }
  46. }
  47. return result;
  48. }
  49.  
  50. public boolean isPalindrome(String s) {
  51. int left = 0, right = s.length() - 1;
  52. while(left < right) {
  53. if(s.charAt(left++) != s.charAt(right--)) return false;
  54. }
  55. return true;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement