回文相关的题目算是算法基础中的基础了。
发现工作后如果不是算法岗,算法能力和算法敏感度真的是会下降,平时mark一些经典算法题有利于保持状态。
题目一:求sentence中的最小分割数,使得分割后所有字符串都是回文。
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”,
Return1since the palindrome partitioning[“aa”,“b”]could be produced using 1 cut.
public class Solution {
public int minCut(String s) {
int len=s.length();
int[] dp=new int[len];
for(int i=0;i<len;i++){
dp[i]=i;
}
for(int i=1;i<len;i++){
if(isPalindrome(s.substring(0,i+1))){
dp[i]=0;
continue;
}
for(int j=0;j<i;j++){
if(isPalindrome(s.substring(j+1,i+1))){
dp[i]=Math.min(dp[i],dp[j]+1);
}
else{
dp[i]=Math.min(dp[i],dp[j]+i-j);
}
}
}
return dp[len-1];
}
public boolean isPalindrome(String str){
if(str==null||str.equals(""))
return true;
int start=0;
int end=str.length()-1;
while(start<end){
if(str.charAt(start)!=str.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}
}
题目二:求sentence中的所有有效分割,使得分割后所有字符串都是回文,输出所有有效分割后的字符串List。
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”]
]
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res=new ArrayList<ArrayList<String>>();
ArrayList<String> palindromeList=new ArrayList<String>();
dfs(s,0,palindromeList,res);
return res;
}
public void dfs(String str, int index, ArrayList<String> pList, ArrayList<ArrayList<String>> res){
if(index==str.length()){
ArrayList<String> mList=new ArrayList<String>();
mList.addAll(pList);
res.add(mList);
return;
}
for(int i=index+1;i<=str.length();i++){
if(isPalindrome(str.substring(index,i))){
pList.add(str.substring(index,i));
dfs(str,i,pList,res);
pList.remove(pList.size()-1);
}
}
}
public boolean isPalindrome(String str){
if(str==null||str.equals(""))
return true;
int start=0;
int end=str.length()-1;
while(start<end){
if(str.charAt(start)!=str.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}
}