2024: 剛開始做leetcode hot100,查閱自己以前寫的題解專欄,發(fā)現(xiàn)沒有這一題,于是加上??赡躭eetcode100更新了吧。我看現(xiàn)在leetcode100官網(wǎng)的題目已經(jīng)是分好類的了,以前我的題解帖子是自己手動(dòng)分類整理的。文章來源地址http://www.zghlxwxcb.cn/news/detail-826553.html
class Solution {
List<List<String>> res;
public List<List<String>> partition(String s) {
res=new ArrayList<>();
dfs(new ArrayList<String>(),s);
return res;
}
public void dfs(ArrayList<String> tmp,String s){
//剩下要處理的
if(s==null||s.length()==0){
res.add(new ArrayList(tmp));
return;
}
for(int i=1;i<=s.length();i++){
//a是已分割,b是未分割
String a=s.substring(0,i);
String b="";
if(i<s.length())
b=s.substring(i);
if(isPalindrome(a)){
tmp.add(a);
dfs(tmp,b);
tmp.remove(tmp.size()-1);
}
}
}
//判斷是否是回文
public boolean isPalindrome(String s){
if(s.length()==0||s.length()==1) return true;
int i=0,j=s.length()-1;
while(i<=j){
if(s.charAt(i)!=s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-826553.html
到了這里,關(guān)于【刷題1】LeetCode 131. 分割回文串 java題解的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!