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()];
    }
};
posted @ 2018-03-31 13:14  森高Slontia  阅读(122)  评论(0编辑  收藏  举报