zoukankan      html  css  js  c++  java
  • 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()];
        }
    };
  • 相关阅读:
    蹉跎之印
    [转]cypress EZ-USB 68013在WIN7 64位下驱动识别方法 && 64位WIN7中禁用驱动程序签名强制
    cnki搜索候选
    [转]和机器学习和计算机视觉相关的数学
    [链接]SPSS 19 最新版破解版及教程下载
    fvtool函数
    [转]html中submit和button的区别(总结)
    [转]SAR与SIGMA DELTA的区别
    LINKAXES matlab plot
    Labview 自动清空前面板显示控件
  • 原文地址:https://www.cnblogs.com/slontia/p/8681814.html
Copyright © 2011-2022 走看看