Skip to content

Commit c3847f1

Browse files
committed
word-break solution
1 parent 62ef031 commit c3847f1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

word-break/lhc0506.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {string} s
3+
* @param {string[]} wordDict
4+
* @return {boolean}
5+
*/
6+
var wordBreak = function(s, wordDict) {
7+
const wordDictSet = new Set(wordDict);
8+
const visited = new Set();
9+
10+
const indexStack = [0];
11+
while(indexStack.length > 0) {
12+
const startIndex = indexStack.pop();
13+
14+
if (visited.has(startIndex)) continue;
15+
visited.add(startIndex);
16+
17+
if (startIndex === s.length) return true;
18+
19+
for (let endIndex = startIndex + 1; endIndex <= s.length; endIndex++) {
20+
const word = s.substring(startIndex, endIndex);
21+
22+
if (wordDictSet.has(word)) {
23+
indexStack.push(endIndex);
24+
}
25+
}
26+
}
27+
28+
return false;
29+
};

0 commit comments

Comments
 (0)