​LeetCode刷题实战139:单词拆分

程序IT圈

共 1175字,需浏览 3分钟

 ·

2020-12-30 17:01

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 单词拆分,我们先来看题面:
https://leetcode-cn.com/problems/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.

题意


给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。


样例

示例 1

输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"

示例 2

输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"
  注意你可以重复使用字典中的单词。

示例 3

输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false


解题


这个题可以使用动态规划来解决。动态规划最重要的是状态的定义,好的状态定义能够使解题非常简便。

状态定义:
dp[i]:长度为i的字符串能否拆成wordDict里边的单词组合

状态转移方程:
dp[i] = dp[j] && substr(j, i) in wordDict, (0 <= j < i)

初始状态:
dp[0]=true

以下是C++代码:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        vector<int> dp(s.size()+1, 0);
        dp[0] = 1;
        unordered_set<string> st(wordDict.begin(), wordDict.end());
        for(int i = 1; i <= s.size(); i++)
        {
            for(int j = 0; j < i; j++)
            {
                auto pos = st.find(s.substr(j, i-j));
                if(dp[j] && pos != st.end())
                {
                    dp[i] = 1;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-120题汇总,希望对你有点帮助!
LeetCode刷题实战121:买卖股票的最佳时机
LeetCode刷题实战122:买卖股票的最佳时机 II
LeetCode刷题实战123:买卖股票的最佳时机 III
LeetCode刷题实战124:二叉树中的最大路径和
LeetCode刷题实战125:验证回文串
LeetCode刷题实战126:单词接龙 II
LeetCode刷题实战127:单词接龙
LeetCode刷题实战128:最长连续序列
LeetCode刷题实战129:求根到叶子节点数字之和
LeetCode刷题实战130:被围绕的区域
LeetCode刷题实战131:分割回文串
LeetCode刷题实战132:分割回文串 II
LeetCode刷题实战133:克隆图
LeetCode刷题实战134:加油站
LeetCode刷题实战135:分发糖果
LeetCode刷题实战136:只出现一次的数字
LeetCode刷题实战137:只出现一次的数字 II
LeetCode刷题实战138:复制带随机指针的链表


浏览 15
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报