[经典] 回文问题(二)
Palindrome Partitioning I
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
动态规划O(N^2),判断ij段是否是回文;DFS,输出结果,根据小长度在前的切法,保证唯一性。
Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
动态规划O(N^2),判断bool isPalindrome[i][j]段是否是回文;动态规划O(N^2),从i到N更新int cutNum[i]的最小值
Palindrome Pairs
Given a list of unique words. Find all pairs of distinct indices (i, j)
in the given list, so that the concatenation of the two words, i.e.words[i] + words[j]
is a palindrome.
Example 1:
Given words
= ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words
= ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
用unordered_map<String, int>存这些数(由于是unique words所以也不需要multimap),复杂度为O(N)