From 00b5e2aa64f49ce9273aca6aa8074d98fe4e489a Mon Sep 17 00:00:00 2001 From: eat to 160 pounds <2915390277@qq.com> Date: Fri, 6 May 2022 15:06:32 +0800 Subject: [PATCH] =?UTF-8?q?131=E5=88=86=E5=89=B2=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E6=9B=B4=E6=B8=85=E6=A5=9A=E7=9A=84typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 41 ++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 10b747cb..7a702898 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -454,31 +454,36 @@ var partition = function(s) { ```typescript function partition(s: string): string[][] { - function isPalindromeStr(s: string, left: number, right: number): boolean { - while (left < right) { - if (s[left++] !== s[right--]) { - return false; + const res: string[][] = [] + const path: string[] = [] + const isHuiwen = ( + str: string, + startIndex: number, + endIndex: number + ): boolean => { + for (; startIndex < endIndex; startIndex++, endIndex--) { + if (str[startIndex] !== str[endIndex]) { + return false } } - return true; + return true } - function backTracking(s: string, startIndex: number, route: string[]): void { - let length: number = s.length; - if (length === startIndex) { - resArr.push(route.slice()); - return; + const rec = (str: string, index: number): void => { + if (index >= str.length) { + res.push([...path]) + return } - for (let i = startIndex; i < length; i++) { - if (isPalindromeStr(s, startIndex, i)) { - route.push(s.slice(startIndex, i + 1)); - backTracking(s, i + 1, route); - route.pop(); + for (let i = index; i < str.length; i++) { + if (!isHuiwen(str, index, i)) { + continue } + path.push(str.substring(index, i + 1)) + rec(str, i + 1) + path.pop() } } - const resArr: string[][] = []; - backTracking(s, 0, []); - return resArr; + rec(s, 0) + return res }; ```