JavaScript 자바스크립트 코딩테스트 04
자주 다루는 코딩테스트 문제를 가져왔습니다.
#146. WordBreak2
코드풀이) JavaScript
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function (s, wordDict, cache = new Map()) {
if (cache.has(s))
return cache.get(s);
if (s.length === 0) {
cache.set(s, []);
return [];
}
const result = [];
for (let word of wordDict) {
const index = s.indexOf(word);
if (index === 0) {
const newStr = s.slice(word.length);
const values = wordBreak(newStr, wordDict, cache);
if (values.length === 0 && newStr.length === 0)
result.push(word);
else {
values.forEach(val => {
result.push(word + ' ' + val);
});
}
}
}
cache.set(s, result);
return result;
}
[문제풀때 필요한 JavaScript 표준 내장 객체인 String prototype method]
var s = 'testcodeboogie'
console.log(s.slice(4))
console.log(s.indexOf('stc'))
console.log(s.indexOf('stc2'))
console.log(s.substring(0, 4))
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function (s, wordDict, cache = new Map()) {
if (cache.has(s))
return cache.get(s);
if (s.length === 0) {
cache.set(s, []);
return [];
}
const result = [];
for (let word of wordDict) {
const index = s.indexOf(word);
if (index === 0) {
const newStr = s.slice(word.length);
const values = wordBreak(newStr, wordDict, cache);
if (values.length === 0 && newStr.length === 0)
result.push(word);
else {
values.forEach(val => {
result.push(word + ' ' + val);
});
}
}
}
cache.set(s, result);
return result;
}
[문제풀때 필요한 JavaScript 표준 내장 객체인 String prototype method]
var s = 'testcodeboogie'
console.log(s.slice(4))
console.log(s.indexOf('stc'))
console.log(s.indexOf('stc2'))
console.log(s.substring(0, 4))
결과(output)
codeboogie
2
-1
test
0 댓글