zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    nginx
    不再想写博客的大众集合教程
    数据结构与算法之算法
    数据结构与算法
    yii2的安装使用
    git的使用方法总结
    php生成图片验证码
    git推送失败的问题
    配置nginx支持thinkphp框架
    centos下的lnmp环境搭建
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13092099.html
Copyright © 2011-2022 走看看