# x 139. Word Break

{% embed url="<https://leetcode.com/problems/word-break/solutions/3831240/easy-and-simple-dp-solution/>" %}

### ideation

Check how many ways to climb stairs

### dp + substring

> time: O(m x n^2), n is the length of string, m is the length of wordDict

> space: O(n)

```js
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];
};
```

### Brute Force: TLE

```js
/**
 * @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);
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/dynamic-programming/x-139.-word-break.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
