LeetCode题解:(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. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".


题目分析

这道题的意思是判断字符串能否由字典里的单词组成,一开始只是以为将字符串分成两部分就可以,进行一些样例测试后才发现可以拆成任意数量的单词,只好重写。
个人思路很简单:

  1. 将字典里的单词一一和字符串进行比对,将符合的索引区间存储在map里,这样就把字典的单词转化成了不同的区间信息;
  2. 建立长度为字符串size+1的bitmap,将第0位置为1,并开始遍历bitmap,做如下操作:假如某一位为1,将所有左端为该位的区间的右端在bitmap中置为1;否则直接跳过。

以下为个人实现(C++ 4ms):

class Solution {
public: 
    map<int, vector<int>> intervals;
    
    void addInterval(string s, string word) {
        int left, right;
        if (word.size() == 0 || s.size() == 0) return;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == word[0]) { // hit first letter
                int j;
                for (j = 1; i + j < s.size() && j < word.size() && s[i + j] == word[j]; j++); // check
                if (j == word.size()) { // match!
                    intervals[i].push_back(i + j);
                }
            }
        }
    }
    
    bool wordBreak(string s, vector<string>& wordDict) {
        bool bitmap[s.size() + 1] = {true};
        for (int i = 0; i < wordDict.size(); i++) {
            addInterval(s, wordDict[i]);
        }
        for (int i = 0; i < s.size(); i++) {
            if (bitmap[i]) {
                for (int j = 0; j < intervals[i].size(); j++) {
                    bitmap[intervals[i][j]] = true;
                }    
            }   
        }
        return bitmap[s.size()];
    }
};
优质内容筛选与推荐>>
1、Linux—修改ssh远程登录信息
2、人生经典20句
3、题目95-众数问题-nyoj20140805
4、BW InfoObject 学习
5、隐藏DLL模块


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号