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()];
        }
    };
  • 相关阅读:
    常用的SQL语句
    解决Pycharm中module 'pip' has no attribute 'main'的问题
    [转]如何使用Fiddler抓取指定浏览器的数据包
    Linux常用命令
    Android:JACK编译错误汇总及解决
    Linux学习:使用 procrank 测量系统内存使用情况
    Android:动态库(.so)调试技巧
    Android 显示系统:Vsync机制
    Android:cmake开发指南
    Android:高通平台性能调试
  • 原文地址:https://www.cnblogs.com/slontia/p/8681814.html
Copyright © 2011-2022 走看看