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 {
            //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
        }
    }
  • 相关阅读:
    RESTful风格的API
    案例:toDoList
    jQuery中的Ajax
    php 使用kafka
    crontab不执行
    php两种实现守护进程的方式
    crontab不执行脚本,手动调测又没有任何问题
    centos7 安装跳板机(堡垒机)
    Ubuntu修改默认键盘布局的方法
    openresty nginx升级版
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12634157.html
Copyright © 2011-2022 走看看