日常切LeetCode水题?(Python)

135.Candy

# Share
# There are N children standing in a line. Each child is assigned a rating value.
# 
# You are giving candies to these children subjected to the following requirements:
# 
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
# What is the minimum candies you must give?

from math import *

class Solution:
    def candy(self, ratings):
        n = len(ratings)
        tmp = [1] * n
        for i in range(n-1):
            if ratings[i] < ratings[i+1]:
                tmp[i+1] = tmp[i]+1
        # print(tmp)
        for i in range(n-1,0,-1):
            if ratings[i-1] > ratings[i]:
                tmp[i-1] = max(tmp[i]+1,tmp[i-1])
        # print(tmp)
        return sum(tmp)

if __name__=='__main__':
    a = Solution()
    res = [1,2,3,4,2,1]
    print(a.candy(res))

139. Word Break

# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
# determine if s can be segmented into a space-separated sequence of one or more dictionary words.
#
# Note:
#
# The same word in the dictionary may be reused multiple times in the segmentation.
# You may assume the dictionary does not contain duplicate words.
# solve:
# dp[j]=true if dp[i-1]=true && s[i:j+1] in dict

from math import *
from typing import *

class Solution:
    def wordBreak(self, s, wordDict):
        dp = [False]*len(s)
        for i in range(len(s)):
            for j in range(i, len(s)):
                if s[i:j+1] in wordDict and (dp[i-1]== True or i-1 == -1):
                    dp[j] = True
        print(dp)
        return dp[-1]

if __name__=='__main__':
    a = Solution()
    s = "leetcode"
    wordlist = ["leet", "code"]
    print(a.wordBreak(s,wordlist))

140. Word Break II

# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, 
# add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
# 
# Note:
# 
# The same word in the dictionary may be reused multiple times in the segmentation.
# You may assume the dictionary does not contain duplicate words.
# 这题不能算水题吧,毕竟自己的做法仅比6%的人快,权当python复习吧
# 下面提供两种做法,第一种就是利用139的结论,但是效率很低,第二种是用字典存当前str能够分解的种类
# 代码通俗易懂,看下就行
from math import *
from typing import *

class Solution:
    def judge(self,s,dict):
        dp = [False] * (len(s)+1)
        dp[0] = True
        for i in range(1,len(s)+1):
            for j in range(0,i):
                if dp[j] and s[j:i] in dict:
                    dp[i] = True
        return dp[len(s)]

    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        ans=[]
        tmp=""
        if s in wordDict:
            ans.append(s)

        for i in range(len(s)):
            tmp+=s[i]
            if tmp in wordDict:
                if self.judge(s[i+1:],wordDict):
                    res = self.wordBreak(s[i+1:],wordDict)
                    for j in res:
                        ans.append(tmp+" "+j)
        return ans

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        return self.helper(s, wordDict, {})

    def helper(self, s, wordDict, res):
        if s in res:
            return res[s]
        if not s:
            return []

        ans = []
        for word in wordDict:
            if not s.startswith(word):
                continue
            if len(word) == len(s):
                ans.append(word)
            else:
                t = self.helper(s[len(word):], wordDict, res)
                for item in t:
                    item = word + ' ' + item
                    ans.append(item)
        res[s] = ans
        # print(res)
        return ans

if __name__=='__main__':
    a = Solution()
    # TEST
    s = "catsanddog"
    lis = ["cat", "cats", "and", "sand", "dog"]
    print(a.wordBreak(s,lis))

 

你可能感兴趣的:(LeetCode每日一题)