1. 程式人生 > >[LeetCode] Word Break 拆分詞句

[LeetCode] 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.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "
apple pen apple".   Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

這道拆分詞句問題是看給定的詞句能分被拆分成字典裡面的內容,這是一道很經典的題目,解法不止一種,考察的範圍很廣,屬於我們必須要熟練掌握的題目。那麼先來想brute force的解法,就拿例子1來分析,如果字典中只有兩個單詞,我們怎麼去判斷,是不是可以將原字串s分成任意兩段,然後再看分成的單詞是否在字典中。注意這道題說是單詞可以重複使用,所以可以分成任意段,而且字典中的單詞可以有很多個,這就增加了題目的難度,很多童鞋就在這裡迷失了,毫無頭緒。那麼,就由博主來給各位指點迷津吧(此處應有掌聲