惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Last Week in AI
Last Week in AI
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
V
Visual Studio Blog
宝玉的分享
宝玉的分享
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园 - 聂微东
S
SegmentFault 最新的问题
博客园 - 司徒正美
罗磊的独立博客
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
美团技术团队
小众软件
小众软件
Jina AI
Jina AI

博客园 - 来自海边的一片云

Binary Tree Maximum Path Sum 解题注意 CodingTMD’s Reading List De Bruijn 序列生成 Word Ladder I ,II 解题思路 suduko及8皇后问题及相关问题的解题思路 leetcode Word Break II 解题思路 Search for a string in an infinite stream of input string. 内存管理 Permutations leetcode Clone Graph leetcode 开弓没有回头箭 combination sum leetcode Combinations leetcode 组合问题 LRU cache Leetcode 重新试着写blog SQL injection Fuzz testing XML库的解析效率 Init()
word break leetcode
来自海边的一片云 · 2014-02-07 · via 博客园 - 来自海边的一片云

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

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

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

这道题目初一看用笨办法,从头到尾,找到一个词然后再找剩下的词,知道找完。

但是这种naive的方法存在bug, 拿字符串 ABCDEFG 而言,如果字典是 AB, ABC, DE, FG, 那划词正确的划法只有 ABC, DE, FG, 如果直接用naive的方法发现根本没法划。

解决这个问题的办法是backtrack。

首先把问题抽象一下,把回溯的递推给写出来

如果输入为NULL,那么算 can break;

如果输入为1 那么就要查字典,看看能不能break。

如果输入为2,AB 那么就要看,首先B是不是在字典里,如果B在字典里,并且A的位置是可分的位置,那么B的位置就是个可分的,否则就不是。

pseudo code:

canwordbreak[0] =true;

for( k->lenght)

for(position = k; position>=0; position--)

 if(substr(position,k) in the dict && canwordbreak[position])

   canwordbreak[k+1] = true;

return canwordbreak[lenth];

    bool wordBreak(string s, unordered_set<string> &dict) {
        
        int len = s.length();
        vector<bool> canwordbreak(len+1, false);
        canwordbreak[0] = true;
        string substr;
  
        for(int k =1; k<=len; k++)
        {
            for(int j=k;j>=0;j--)
            {
                substr = s.substr(j,k-j);
                
                if(dict.find(substr)!=dict.end() && canwordbreak[j])
                {
                    canwordbreak[k]= true;
                    break;
                }
            }
        }
        return canwordbreak[len];
                
    }