Open Choozii opened 1 year ago
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
const cache = {};
const words = {};
for(let i=0;i<wordDict.length;i++){
words[wordDict[i]] = true;
}
const recursive = (word) => {
if(cache[word] !== undefined){
return cache[word];
}
if(words[word]){
return true;
}
for(let i=1;i<word.length;i++){
const left = word.slice(0,i);
const right = word.slice(i);
if(words[left]){
if(recursive(right)){
cache[word] = true;
return true;
}else if(!recursive(right)){
cache[word] = false;
}
}
}
return false;
}
return recursive(s);
};
Check how many ways to climb stairs
time: O(m x n^2), n is the length of string, m is the length of wordDict
space: O(n)
var wordBreak = function(s, wordDict) {
const arr = new Array(s.length + 1).fill(false);
arr[0] = true;
for (let i = 1; i < arr.length; i++) {
for (const word of wordDict) {
const possible = arr[i - word.length];
if (possible === true) {
const sub = s.substring(i - word.length, i);
if (sub === word) {
arr[i] = true;
break;
}
}
}
}
return arr[s.length];
};
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
let status = {
done: false,
};
var wordBreak = function(s, wordDict) {
status = {
done: false,
flag: false,
};
validate(s, wordDict);
return status.flag;
};
function validate(s, wordDict) {
if (status.flag === true) {
return;
}
if (s.trim().length === 0) {
status.flag = true;
return;
}
for (let i = 0; i < wordDict.length; i++) {
const currWord = wordDict[i];
const regex = new RegExp(currWord, '');
if (s.includes(currWord)) {
const newStr = s.replace(regex, ' ')
validate(newStr, wordDict);
}
}
}
타임아웃 나던 풀이
수정한 풀이