Skip to content

Commit

Permalink
add: solve #271 Word Break with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yjason-K committed Jan 11, 2025
1 parent 6bed3de commit de48951
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions word-break/Yjason-K.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด ๋‹จ์–ด ์‚ฌ์ „์— ์žˆ๋Š” ๋‹จ์–ด๋“ค๋กœ ๋‚˜๋ˆ„์–ด์งˆ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.
*
*
* @param {string} s - ํ™•์ธํ•  ๋ฌธ์ž์—ด
* @param {string[]} wordDict - ๋‹จ์–ด ์‚ฌ์ „
* @returns {boolean} ๋ฌธ์ž์—ด์ด ๋‹จ์–ด๋กœ ์™„๋ฒฝํžˆ ๋‚˜๋ˆ„์–ด์งˆ ์ˆ˜ ์žˆ์œผ๋ฉด `true`, ์•„๋‹ˆ๋ฉด `false`
*
* ์‹œ๊ฐ„ ๋ณต์žก์„ฑ O(n * m * k)
* - n: ๋ฌธ์ž์—ด s ๊ธธ์ด
* - m: ๋‹จ์–ด ์‚ฌ์ „ ๊ธธ์ด
* - k: ๋‹จ์–ด ์‚ฌ์ „ ๋‚ด ๋‹จ์–ด ๊ธธ์ด
*
* ๊ณต๊ฐ„ ๋ณต์ž ์„ฑ O(n)
* - ๋ฉ”๋ชจ์ด์ œ์ด์…˜(memo) ๋ฐ ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ํฌ๊ธฐ๊ฐ€ ๋ฌธ์ž์—ด ๊ธธ์ด n์— ๋น„๋ก€.
*/
function wordBreak(s: string, wordDict: string[]): boolean {
const memo: Record<number, boolean> = {};

/**
* @param {number} start - ํ˜„์žฌ ์‹œ์ž‘ idx
* @returns {boolean} ์ฃผ์–ด์ง„ idx ๋ถ€ํ„ฐ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ์œผ๋ฉด true
*/
const dfs = (start: number): boolean => {
if (start in memo) return memo[start];
if (start === s.length) return (memo[start] = true);

for (const word of wordDict) {
if (s.startsWith(word, start) && dfs(start + word.length)) {
return (memo[start] = true);
}
}

return (memo[start] = false);
};

return dfs(0);
}

0 comments on commit de48951

Please sign in to comment.