Cynthia
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 【LeetCode】0139. Word Break date: 2018-12-21 is_modified: false disqus: cynthiahackmd categories: - "面試刷題" tags: - "LeetCode" --- {%hackmd @CynthiaChuang/Github-Page-Theme %} <br> 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. <!--more--> <br> > **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. <br> **Example 1:** ```python Input: s = "leetcode", wordDict = ["leet", "code"] Output: True Explanation:Return true because "leetcode" can be segmented as "leet code". ``` **Example 2:** ```python Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: True Explanation:Return true because "leetcode" can be segmented as "leet code". ``` **Example 3:** ```python Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: False ``` <br> **Related Topics:** `Dynamic Programming` ## 解題邏輯與實作 這題是要將題目給定的句子拆解成字典中的單字。第一個想到的就是我最愛的暴力法,拆、拆、拆就對了! ### 遞迴 也就是暴力解,想法很簡單,就是把句子拆成前後兩句下去查,一旦有一種拆法可以查的到就回傳 True,否則回傳 False。當然為了避免大量重複計算,另外用 HashTable 記錄查過得結果,解法如下: 1. 查詢此單字是否存在於字典中 1. 有,則回傳 True 2. 否,則向下執行 2. 使用一個指標由前向後遍歷此單字,並依指標位置,將單字拆成前後部份並呼叫遞迴傳入,唯有當前後部份皆可在字典中查到時才回傳 True,否則繼續向後遍歷。 3. 若遍歷完整個字串皆無法找到拆解法則回傳 False ```python= class Solution: def __init__(self, mydict=None): self.mydict = mydict self.memo = {} def set_dict(self,mydict): self.mydict = mydict def wordBreak(self, s, wordDict): self.set_dict(set(wordDict)) return self.check(s) def check(self, s): length = len(s) if s in self.memo: return self.memo.get(s) if length <= 0 or s in self.mydict: self.memo[s] = True return True result = False for i in range(1, length): result = self.check(s[:i]) and self.check(s[i:]) if result : break self.memo[s] = result return result ``` 但果不期然,效率有點差跑出了個 740 ms, 1.20% 的成績,摸摸鼻子改寫 DP 去。 ### Dynamic Programming 這題大概是難得我這幾天整理的題目中,DP 解終於不是欠著的題目了 XDDD 這邊使用了一個 dp 陣列記錄結果,其中 dp[i] 中記錄著字串 s[:i] 是否能夠拆解,接下來若是 s[i:j] 也可以進行拆解,因為已知 s[:i] 可拆解,又s[i:j] 可拆解,故 s[:j] 可拆解,因此記錄 dp[j] 為 True,按這關係推導,最後就可以判斷目標字串是否可以被拆解。 ```python= class Solution: def wordBreak(self, s, wordDict): n = len(s) dp = [False] * (n + 1) dp[0] = True words = set(wordDict) for j in range(n): for i in range(j, -1, -1): if dp[i] and s[i:j + 1] in words: dp[j + 1] = True break return dp[n] ``` 這效能果然好上不少,跑出了 68 ms, 15.49% 的成績。 ### Dynamic Programming 改進版 看到我的 code 雖然有比上次進步,但其實無條件進位也才 16% 而已,有些好奇前面 code是怎樣的,所以手賤點了前段班的 code 出來看。 發現他雖然也是用 DP 解,但他加上了點巧思,與我不同的是他是由後向前遍歷,並寫加上了檢查距離的限制,限制在字典中最長的單字長度上,檢查再多也沒有意義,因為字典就沒有這麼長的單字咩。最後跑出來成績為 36 ms, 99.65% 。 ```python= class Solution: def wordBreak(self, s, wordDict): words = set(wordDict) maxLen = 0 for word in wordDict: maxLen = max(maxLen, len(word)) n = len(s) dp = [False] * (n + 1) dp[n] = True for i in range(n - 1, -1, -1): for j in range(i + 1, min(i + maxLen, n) + 1): if dp[j] and s[i:j] in words: dp[i] = True break return dp[0] ``` ## 其他連結 1. [【LeetCode】0000. 解題目錄](/x62skqpKStKMxRepJ6iqQQ) <br><br> > **本文作者**: 辛西亞.Cynthia > **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/LeetCode-0139-Word-Break) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/LeetCode-0139-Word-Break) > **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully