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
        }
    }
  • 相关阅读:
    没有精神分裂的测试不是一个好家长
    防火墙中配置开放 8080端口--续上一篇
    rocketMQ(一)基础环境
    如何做一个对账系统
    通用对账系统介绍与设计(上)
    pdf转图片
    虚拟机加载类机制
    jenkins
    zookeeper和dubbo
    正则日常积累
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13092099.html
Copyright © 2011-2022 走看看