2020-05-03 131. Palindrome Partitioning Medium

Given a string?s, partition?s?such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of?s.

Example:

Input:"aab"Output:[? ["aa","b"],? ["a","a","b"]]


這題一開始想法是每個(gè)字符有兩種情況:加到當(dāng)前字符串,或加到下一個(gè)字符串。后來看了下別人的答案,其實(shí)直接先判斷是否回文,再進(jìn)行l(wèi)ist的add操作,更省時(shí)間。


class Solution {

? ? public List<List<String>> partition(String s) {

? ? ? ? // System.out.println("input: " + s);

? ? ? ? List<List<String>> res = new LinkedList<>();

? ? ? ? LinkedList<String> cur = new LinkedList<String>();

? ? ? ? backtrace(cur, res, s, 0);

? ? ? ? return res;

? ? }


? ? private void backtrace(LinkedList<String> cur, List<List<String>> res, String s, int index) {

? ? ? ? // System.out.println(String.format("cur: %s, index: %d, s: %s", Arrays.deepToString(cur.toArray()), index, s));

? ? ? ? if (index == s.length()) {

? ? ? ? ? ? res.add(new ArrayList<>(cur));

? ? ? ? ? ? return;

? ? ? ? }


? ? ? ? for (int r = index; r < s.length(); r++) {

? ? ? ? ? ? if (isPalindrome(s, index, r)) {

? ? ? ? ? ? ? ? cur.add(s.substring(index, r + 1));

? ? ? ? ? ? ? ? backtrace(cur, res, s, r + 1);

? ? ? ? ? ? ? ? cur.removeLast();

? ? ? ? ? ? }

? ? ? ? }

? ? }


? ? private boolean isPalindrome(String s, int l, int r) {

? ? ? ? while (l < r) {

? ? ? ? ? ? if (s.charAt(l) != s.charAt(r)) return false;

? ? ? ? ? ? l++; r--;

? ? ? ? }

? ? ? ? return true;

? ? }

}



還要吐槽leetcode,這題我完全一樣的答案,提交上去有時(shí)候4ms,有時(shí)候2ms,弄得百分比也不一樣,還以為代碼還有哪里有問題,結(jié)果拷貝了2ms的答案跑出來也要5ms左右

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容