본문 바로가기

리트코드/midium

[리트코드] 131. Palindrome Partitioning - js

반응형

1. 문제

https://leetcode.com/problems/palindrome-partitioning/

 

Palindrome Partitioning - LeetCode

Can you solve this real interview question? Palindrome Partitioning - Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.   Example 1: Input: s = "aab" Output: [["a","

leetcode.com

2. 코드

이 문제는 dfs를 사용하여 풀었다.

/**
 * @param {string} s
 * @return {string[][]}
 */
var partition = function(s) {
    let answer = [];
    
    const check = (arr,left) => {
        if(!left.length && arr.length) answer.push(arr);

        for(let i=1;i<=left.length;i++){
            let word = left.slice(0,i);
            if(isPalindrome(word)){
                let newArr = arr.slice();
                newArr.push(word);
                let newLeft = left.slice(i);
                check(newArr,newLeft);
            }
        }
    }

    check([],s);

    return answer;
};

const isPalindrome = (str) => {
    let back = str.split("").reverse().join("");

    if(str === back) return true;
    else false;
}
반응형