반응형
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;
}
반응형
'리트코드 > midium' 카테고리의 다른 글
[리트코드] 189. Rotate Array - js (0) | 2023.08.13 |
---|---|
[리트코드] 238. Product of Array Except Self - js (0) | 2023.08.12 |
[리트코드] 739. Daily Temperatures - js (0) | 2023.08.10 |
[리트코드] 215. Kth Largest Element in an Array (0) | 2023.08.09 |
[리트코드] 49. Group Anagrams - js (0) | 2023.08.08 |