139. Word Break

package LeetCode_139

/**
 * 139. Word Break
 * https://leetcode.com/problems/word-break/description/
 *
 * Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
 * */
class Solution {
    fun wordBreak(s: String, wordDict: List<String>): Boolean {
        //method 1: backtracking, TLE
        //val result = helper(s,wordDict,"")

        //method 2: backtracking+memorized, Time complexity: O(2^n), Space complexity:O(n)
        val map = HashMap<String, Boolean>()
        val set = HashSet<Char>()
        //check every latter of s if exist in set first
        for (word in wordDict) {
            for (c in word) {
                set.add(c)
            }
        }
        for (c in s) {
            if (!set.contains(c)) {
                return false
            }
        }
        return helper(s, wordDict, "", map)
    }

    private fun helper(s: String, wordDict: List<String>, temp: String, map: HashMap<String, Boolean>): Boolean {
        if (map.containsKey(temp)) {
            return map.get(temp)!!
        }
        if (s.length < temp.length) {
            return false
        }
        for (i in 0 until temp.length) {
            if (s[i] != temp[i]) {
                return false
            }
        }
        if (s.length == temp.length) {
            return true
        }
        for (word in wordDict) {
            if (helper(s, wordDict, temp + word, map)) {
                map.put(temp, true)
                return true
            }
        }
        map.put(temp, false)
        return false
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/12634157.html