You are given a string s
. You can convert s
to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: s = "aacecaaa" Output: "aaacecaaa"
Example 2:
Input: s = "abcd" Output: "dcbabcd"
Constraints:
0 <= s.length <= 5 * 104
s
consists of lowercase English letters only.
思路:首先如何满足palindrom,从开始数,找到最长的palindrome,然后把剩余不是的部分倒转拼到左侧即实现了palindrome
解法1:暴力尝试所有情况,时间复杂读为O(N2)
解法一就不写了
解法2: 使用rolling hash,如果是palindrome的话,从左右两侧计算hash值应该是同一个值
因此,我们可以从第一个字母开始逐步向后计算hash值,一个维护从前到后的hash值,一个维护从后向前的hash值
class Solution { public String shortestPalindrome(String s) { if("".equals(s)) return s; int sum = 0, reverse = 0; int pos = 0; int power = 1; int mod = 19999999; for(int i=0;i<s.length();i++){ int c = s.charAt(i)-'a'; sum = (sum*26+c)%mod; reverse = (c*power+reverse)%mod; power = power*26%mod; if( sum==reverse && isParlindrom(s.substring(0,i+1)) ){ pos = i; } } return (new StringBuilder(s.substring(pos+1)).reverse()).toString()+s; } private boolean isParlindrom(String s){ int left = 0,right = s.length()-1; while(left<right){ if(s.charAt(left) == s.charAt(right)){ left++;right--; } else return false; } return true; } }
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000
s
consists of lowercase English letters.
解法: 只需要简单的从左侧开始, 以当前字母和当前两个字母为中心向两侧判定计算palindrome
class Solution { int count = 0; public int countSubstrings(String s) { int len = s.length();
//以逐个字母为中心进行计算 for(int i=0;i<len;i++){ valid(s,i,i);//计算奇数情况 if(i<len-1) valid(s,i,i+1);//计算偶数个情况 } return count; } public void valid(String s, int left,int right){ int len = s.length(); while(left>=0 && right<len){ if(s.charAt(left)==s.charAt(right)){ left--;right++; count++; } else break; } } }
Given a string s
and an integer k
, return true
if s
is a k
-palindrome.
A string is k
-palindrome if it can be transformed into a palindrome by removing at most k
characters from it.
Example 1:
Input: s = "abcdeca", k = 2 Output: true Explanation: Remove 'b' and 'e' characters.
Example 2:
Input: s = "abbababa", k = 1 Output: true
Constraints:
1 <= s.length <= 1000
s
consists of only lowercase English letters.1 <= k <= s.length
解法:lcs,实际这个题目可以转化为longest common subsequence 问题,我们只要得到这个字符串与其反转后字符串的lcs,那么剩余的就是需要删除的个数
class Solution { public boolean isValidPalindrome(String s, int k) {
//得到lcs int max = dfs(s,0,s.length()-1,new Integer[s.length()][s.length()]); return s.length()-max<=k;//长度-lcs 即为需要删除的个数 } private int dfs(String s,int left,int right,Integer[][] mem){ if(left >= s.length() || right<0) return 0; if(mem[left][right]!=null) return mem[left][right]; if(s.charAt(left) == s.charAt(right)){ mem[left][right] = dfs(s, left+1, right-1,mem)+1; } else{ mem[left][right] = Math.max(dfs(s, left+1, right,mem),dfs(s, left, right-1,mem)); } return mem[left][right]; } }
516. Longest Palindromic Subsequence
Given a string s
, find the longest palindromic subsequence's length in s
.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: s = "bbbab" Output: 4 Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd" Output: 2 Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
1 <= s.length <= 1000
s
consists only of lowercase English letters.
这个题是上一题的套娃题
class Solution { public int longestPalindromeSubseq(String s) { return dfs(s, 0, s.length()-1, new Integer[s.length()][s.length()]); } private int dfs(String s,int left,int right,Integer[][] mem){ if(left>=s.length() || right<0) return 0; if(mem[left][right]!=null) return mem[left][right]; if(s.charAt(left) == s.charAt(right)){ mem[left][right]=dfs(s, left+1, right-1, mem)+1; } else{ mem[left][right]= Math.max(dfs(s, left+1, right,mem), dfs(s,left, right-1,mem)); } return mem[left][right]; } }
131. Palindrome Partitioning
Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
A palindrome string is a string that reads the same backward as forward.
Example 1:
Input: s = "aab" Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a" Output: [["a"]]
Constraints:
1 <= s.length <= 16
s
contains only lowercase English letters.
解法:
aab / | \ / | \ a|ab aa|b aab| / | | a|a|b a|ab| aa|b| / a|a|b|
class Solution { public List<List<String>> partition(String s) { List<List<String>> result = new ArrayList(); dfs(s, new ArrayList(), result); return result; } private void dfs(String s, List<String> curr, List<List<String>> result){ if("".equals(s)){ result.add(new ArrayList(curr)); return; } for(int i=0;i<s.length();i++){ if(isParlindrom(s.substring(0,i+1))){ curr.add(s.substring(0,i+1)); dfs(s.substring(i+1), curr, result); curr.remove(curr.size()-1); } } } private boolean isParlindrom(String s){ int left = 0,right = s.length()-1; while(left<right){ if(s.charAt(left) == s.charAt(right)){ left++;right--; } else return false; } return true; } }
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
.
Example 1:
Input: s = "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:
Input: s = "a" Output: 0
Example 3:
Input: s = "ab" Output: 1
Constraints:
1 <= s.length <= 2000
s
consists of lowercase English letters only.
aab / | \ / | \ a|ab aa|b aab| / \ | a|a|b a|ab| aa|b|
class Solution { public int minCut(String s) { return minCut(s, 0, new Integer[s.length()])-1; } private int minCut(String s, int curr, Integer[] mem){ if(curr == s.length()) return 0; if(mem[curr]!=null) return mem[curr]; int min = s.length(); for(int i=curr;i<s.length();i++){ if(isPalindrome(s,curr,i)){ min = Math.min(min,1+minCut(s,i+1,mem)); } } mem[curr]=min; return min; } private boolean isPalindrome(String s,int left,int right){ while(left<right){ if(s.charAt(left) == s.charAt(right)){ left++;right--; } else return false; } return true; } }
5. Longest Palindromic Substring
Given a string s
, return the longest palindromic substring in s
.
Example 1:
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters.
class Solution { public String longestPalindrome(String s) { int pos = 0,max = 1; //以逐个字符为中心进行palindrome判定 for(int i=0;i<s.length();i++){ //判断以当前字符为中心的palindrome长度 int curr = isPalindrome(s, i, i); if(max < curr){ max = curr; pos = i-max/2; } //判断以当前两个字符为中心的palindrome的长度 curr = isPalindrome(s, i, i+1); if(max < curr){ max = curr; pos = i-(max-1)/2; } } //返回最长的那个 return s.substring(pos, pos+max); } private int isPalindrome(String s, int left, int right){ int max = 0; while(left>=0 && right<s.length()){ if(s.charAt(left) == s.charAt(right)){ max = right-left+1; left--;right++; } else return max; } return max; } }
Given a palindromic string of lowercase English letters palindrome
, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly smaller than the corresponding character in b
. For example, "abcc"
is lexicographically smaller than "abcd"
because the first position they differ is at the fourth character, and 'c'
is smaller than 'd'
.
Example 1:
Input: palindrome = "abccba" Output: "aaccba" Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba". Of all the ways, "aaccba" is the lexicographically smallest.
Example 2:
Input: palindrome = "a" Output: "" Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
Constraints:
1 <= palindrome.length <= 1000
palindrome
consists of only lowercase English letters.
解法:
case1:
some place can replace to a
bcb -> acb
case2:
no place can replace to a
aaa -> aab
aba -> abb
class Solution { public String breakPalindrome(String palindrome) { int len = palindrome.length(); if(len==1) return ""; for(int i=0;i<len;i++){ //如果这个字母是最中间的那个,替换了不管用,直接跳过 if(len%2==1 && i==len/2) continue; //如果有不是a的字母,替换为a即得到最小的 if(palindrome.charAt(i)!='a') return palindrome.substring(0,i)+'a'+palindrome.substring(i+1); } //如果没有可以替换为a的,那么只能把最后一个字母替换为b也使其最小 return palindrome.substring(0,len-1)+'b'; } }
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s
, return the longest happy prefix of s
. Return an empty string ""
if no such prefix exists.
Example 1:
Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Constraints:
1 <= s.length <= 105
s
contains only lowercase English letters.
解法: rolling hash
class Solution { public String longestPrefix(String s) { //rolling hash long head =0,tail = 0; long pow = 1,mod = (long)1e9+7; int max = 0; int len = s.length(); for(int i=0;i<s.length()-1;i++){ int vhead = s.charAt(i) - 'a'; int vtail = s.charAt(len-i-1) - 'a'; head = (head*26 + vhead) % mod; tail = (vtail*pow + tail) % mod; pow = pow*26%mod; if(head==tail) max = Math.max(max, i+1); } return s.substring(0,max); } }
1023. Camelcase Matching
Given an array of strings queries
and a string pattern
, return a boolean array answer
where answer[i]
is true
if queries[i]
matches pattern
, and false
otherwise.
A query word queries[i]
matches pattern
if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
Example 1:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".
Example 2:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".
Example 3:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".
Constraints:
1 <= pattern.length, queries.length <= 100
1 <= queries[i].length <= 100
queries[i]
andpattern
consist of English letters.
class Solution { public List<Boolean> camelMatch(String[] queries, String pattern) { List<Boolean> list = new ArrayList(); for(String query:queries){ list.add(check(query, pattern)); } return list; } private boolean check(String query, String pattern){ int i=0,j=0; //quer 必须一直走到头 while(i < query.length() ){ char c = query.charAt(i); //如果与pattern一致,那么同时右移 if( j < pattern.length() && c == pattern.charAt(j)){ i++;j++; } else{ //如果query是大写,那么直接返回false if(Character.isUpperCase(c)) return false; //如果是小写,那么右移query指针 else i++; } } //判定pattern指针是否移到了最右侧 return j==pattern.length(); } }