mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
131分割字符串更清楚的typescript版本
This commit is contained in:
@ -454,31 +454,36 @@ var partition = function(s) {
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
function partition(s: string): string[][] {
|
function partition(s: string): string[][] {
|
||||||
function isPalindromeStr(s: string, left: number, right: number): boolean {
|
const res: string[][] = []
|
||||||
while (left < right) {
|
const path: string[] = []
|
||||||
if (s[left++] !== s[right--]) {
|
const isHuiwen = (
|
||||||
return false;
|
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 {
|
const rec = (str: string, index: number): void => {
|
||||||
let length: number = s.length;
|
if (index >= str.length) {
|
||||||
if (length === startIndex) {
|
res.push([...path])
|
||||||
resArr.push(route.slice());
|
return
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
for (let i = startIndex; i < length; i++) {
|
for (let i = index; i < str.length; i++) {
|
||||||
if (isPalindromeStr(s, startIndex, i)) {
|
if (!isHuiwen(str, index, i)) {
|
||||||
route.push(s.slice(startIndex, i + 1));
|
continue
|
||||||
backTracking(s, i + 1, route);
|
}
|
||||||
route.pop();
|
path.push(str.substring(index, i + 1))
|
||||||
|
rec(str, i + 1)
|
||||||
|
path.pop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
rec(s, 0)
|
||||||
const resArr: string[][] = [];
|
return res
|
||||||
backTracking(s, 0, []);
|
|
||||||
return resArr;
|
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user