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 {
        val map = HashMap<String, Boolean>()
        val set = HashSet<String>()
        for (word in wordDict) {
            set.add(word)
        }
        return dfs(s, set, map)
    }

    /**
     * soulution: backtracking+memorized, Time complexity:O(2^n), Space complexity:O(n)
     * */
    private fun dfs(s: String, set: HashSet<String>, map: HashMap<String, Boolean>): Boolean {
        if (map.contains(s)) {
            return map.get(s)!!
        }
        if (set.contains(s)) {
            map.put(s, true)
            return true
        }
        //check left side and right side by each levels
        for (i in 1 until s.length) {
            val left = s.substring(0, i)
            val right = s.substring(i)
            if (set.contains(right) && dfs(left, set, map)) {
                map.put(s, true)
                return true
            }
        }
        map.put(s, false)
        return false
    }
}

 

posted @ 2020-06-11 11:20  johnny_zhao  阅读(132)  评论(0编辑  收藏  举报