|
| 1 | + |
| 2 | +>仰望星空的人,不应该被嘲笑 |
| 3 | +
|
| 4 | +## 题目描述 |
| 5 | + |
| 6 | +给定一个字符串 `s`,将 `s` 分割成一些子串,使每个子串都是回文串。 |
| 7 | + |
| 8 | +返回 s 所有可能的分割方案。 |
| 9 | + |
| 10 | +示例: |
| 11 | + |
| 12 | +```javascript |
| 13 | +输入: "aab" |
| 14 | +输出: |
| 15 | +[ |
| 16 | + ["aa","b"], |
| 17 | + ["a","a","b"] |
| 18 | +] |
| 19 | +``` |
| 20 | + |
| 21 | +来源:力扣(LeetCode) |
| 22 | +链接:https://leetcode-cn.com/problems/palindrome-partitioning |
| 23 | +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
| 24 | + |
| 25 | + |
| 26 | +## 解题思路 |
| 27 | +借鉴 <a href="https://leetcode-cn.com/problems/palindrome-partitioning/solution/chui-su-fa-jian-dan-jie-ti-chao-qing-xi-tu-li-by-z/">zesong-wang-c</a> 大佬的图解 |
| 28 | + |
| 29 | +本题采用回溯思想,看上图基本已经明白,每次进行一次切割,直到切到最后一个元素,然后压入结果集合里,期间对于每次切割的字符串,我们判断一下是否是回文,如果不是,直接减掉即可。 |
| 30 | + |
| 31 | +和组合的思想有点类似。 |
| 32 | + |
| 33 | +```javascript |
| 34 | +// 判断是否是回文 |
| 35 | +function isPal(str) { |
| 36 | + let len = Math.floor(str.length / 2); |
| 37 | + if (len === 0) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + let add = str.length % 2 === 0 ? 0 : 1; |
| 41 | + let subStr = str.slice(0, len); |
| 42 | + for (let i = 0; i < len; i++) { |
| 43 | + if (subStr[len - i - 1] !== str[len + add + i]) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + } |
| 47 | + return true; |
| 48 | +} |
| 49 | +var partition = function (s) { |
| 50 | + let res = []; |
| 51 | + let dfs = (cur, start) => { |
| 52 | + // 当前已经到达了最后一个元素 |
| 53 | + if (start >= s.length) { |
| 54 | + res.push(cur.slice()); |
| 55 | + return; |
| 56 | + } |
| 57 | + for (let i = start; i < s.length; i++) { |
| 58 | + // 字符串切割 |
| 59 | + let str = s.slice(start, i + 1); |
| 60 | + if (str && isPal(str) ) { |
| 61 | + cur.push(str); |
| 62 | + dfs(cur, i + 1); |
| 63 | + // 回溯 |
| 64 | + cur.pop(); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + dfs([], 0); |
| 69 | + return res; |
| 70 | +}; |
| 71 | +``` |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | +## 最后 |
| 79 | +文章产出不易,还望各位小伙伴们支持一波! |
| 80 | + |
| 81 | +往期精选: |
| 82 | + |
| 83 | +<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a> |
| 84 | + |
| 85 | +<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a> |
| 86 | + |
| 87 | +小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you! |
| 88 | + |
| 89 | + |
| 90 | +<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~ |
| 91 | + |
| 92 | + |
| 93 | + |
| 94 | +```javascript |
| 95 | +学如逆水行舟,不进则退 |
| 96 | +``` |
| 97 | + |
| 98 | + |
0 commit comments