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
        }
    }
  • 相关阅读:
    [Apache commons系列]DBUtils 示例代码
    关于syslog
    Phoenix Tips (1)
    Phoenix 常用函数
    Phoenix 的数据类型
    最简单的Phoenix 访问 HBase例子
    SVNKIT 主要方法
    Linux 集群时钟同步
    Linux 集群时钟同步
    Linux 下定时提交SVN
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12634157.html
Copyright © 2011-2022 走看看