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

推荐订阅源

U
Unit 42
Vercel News
Vercel News
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
量子位
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)

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

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];
                
    }