leetcode 131. Palindrome Partitioning | 131. 分割回文串(递归解法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 131. Palindrome Partitioning | 131. 分割回文串(递归解法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/palindrome-partitioning/
題解
中規(guī)中矩的遞歸,因為每一層都需要在上一層保存好的 list 的基礎(chǔ)上繼續(xù),而且不能影響下一層遞歸,所以做了一些 local 化的操作,自我感覺不是很優(yōu)雅。
更好的解法可以參考:官方題解
class Solution {public List<List<String>> partition(String s) {List<List<String>> result = new ArrayList<>();List<String> curList = new ArrayList<>();process(s, 0, curList, result);return result;}public void process(String s, int begin, List<String> curList, List<List<String>> result) {if (begin >= s.length()) return;if (isPalindrome(s, begin, s.length() - 1)) {List<String> temp = new ArrayList<>(curList);temp.add(s.substring(begin, s.length()));result.add(temp);}List<String> local;for (int i = begin; i < s.length(); i++) {if (isPalindrome(s, begin, i)) {local = new ArrayList<>(curList);local.add(s.substring(begin, i + 1));process(s, i + 1, local, result);}}}public boolean isPalindrome(String s, int i, int j) {while (i < j) {if (s.charAt(i) != s.charAt(j)) return false;i++;j--;}return true;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 131. Palindrome Partitioning | 131. 分割回文串(递归解法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 384. Shuffl
- 下一篇: leetcode 373. Find K