Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

分割回文串 #2

Open
Aras-ax opened this issue Feb 28, 2019 · 0 comments
Open

分割回文串 #2

Aras-ax opened this issue Feb 28, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Feb 28, 2019

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: "aab"
输出:
[
  ["aa","b"],
  ["a","a","b"]
]

解答

/**
 * @param {string} s
 * @return {string[][]}
 */
var partition = function(s) {
    let res = [];

    if (s === null || s.length === 0) {
        return res;
    }

    let len = s.length,
        arr = [];

    function palindrome(s, start) {
        if (start === len) {
            res.push([...arr]);
            return;
        }
        for (let i = start; i < len; i++) {
            let curStr = s.substring(start, i + 1);
            if (isPalindrome(s, start, i)) {
                arr.push(curStr);
                palindrome(s, i + 1);
                arr.pop();
            }
        }
    }

    palindrome(s, 0);
    return res;
}


/**
 * 是否是回文
 */
function isPalindrome(s, left, right) {
    while (left < right && s[left] === s[right]) {
        left++;
        right--;
    }
    return left >= right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant