0
点赞
收藏
分享

微信扫一扫

131.分割回文串

大自然在召唤 2022-04-03 阅读 66
java

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例: 输入: “aab” 输出: [ [“aa”,“b”], [“a”,“a”,“b”] ]

class Solution {
List<List<String>> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
dfs(s,0);
return res;
}
//回溯
public void dfs(String s,int start){
if(start >= s.length()){
res.add(new ArrayList<>(path));//当切割位置为字符串串末尾时结束
}

for(int i = start;i < s.length();i++){
if(isSame(s,start,i)){
String str = s.substring(start,i+1);
path.add(str);
}else{
continue;
}
dfs(s,i + 1);
path.remove(path.size() - 1);//回溯
}
}
//判断是否为回文串
public boolean isSame(String s,int start,int end){
while(start <= end){
if(s.charAt(start++) != s.charAt(end--)){
return false;
}
}
return true;
}
}
举报

相关推荐

0 条评论