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

分割回文串-131 #67

Open
sl1673495 opened this issue Jun 11, 2020 · 0 comments
Open

分割回文串-131 #67

sl1673495 opened this issue Jun 11, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 11, 2020

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

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

递归全排列

尝试所有的下标做起点,所有的下标作为终点,递归暴力判断。

/**
 * @param {string} s
 * @return {string[][]}
 */

let partition = function (s) {
  let n = s.length
  let ret = []
  let find = function (start, prev) {
    // 最少分割一个字符 最多分割到末尾前一位
    for (let i = 1; i <= n; i++) {
      let end = start + i
      let cur = s.substring(start, end)
      if (cur) {
        let res = prev.concat(cur)
        if (isPalindrome(cur)) {
          if (end === n) {
            ret.push(res)
          } else {
            find(start + i, res)
          }
        }
      }
    }
  }
  find(0, [])
  return ret
}

function isPalindrome(s) {
  if (!s) {
    return false
  }
  let i = 0
  let j = s.length - 1

  while (i < j) {
    let head = s[i]
    let tail = s[j]

    if (head !== tail) {
      return false
    } else {
      i++
      j--
    }
  }
  return true
}
@sl1673495 sl1673495 added DFS 深度优先遍历 递归与回溯 and removed DFS 深度优先遍历 labels Jun 11, 2020
Repository owner deleted a comment from jinfang12345 Jun 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant