Word Break Ⅱ

问题描述

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

算法分析

1、从字符串开始处分析,如果第一个单词是cat,则该组剩余的单词是在sanddog 里提取,即sanddog

2、如果第一个单词是cats ,则该组剩余的单词在在anddog 里提取,即anddog

3、很明显这是一个递归问题,找出一个单词后递归查找剩余的单词。

4、使用一个unsorted_map<string, vector<string>> 数据结构存储每一次递归查找一个字符串的结果。查找"cat" 的结果为["cat"] ;查找"cats" 的结果为["cats"] ;查找"catsand" 的结果为["cat sand", "cats and"] ;查找"catsanddog" 的结果为["cat sand dog", "cats and dog"]

C++实现

class Solution {
privateunordered_map<string, vector<string>> m;

    vector<string> combine(string word, vector<string> prev) {
        for(int i = 0; i < prev.size();++i)
            prev[i] += " " + word;
        return prev;
    }

    bool isaWord(string s, vector<string>& wordDict) {
        vector<string>::iterator it = find(wordDict.begin(), wordDict.end(), s);
        return (it != wordDict.end());
    }

public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        if (m.count(s)) 
            return m[s]; //take from memory
        vector<string> result;

        if (isaWord(s, wordDict))  //a whole string is a word
            result.push_back(s);
        for(int i = 1;i < s.size(); ++i) {
            string word = s.substr(i);
            if(isaWord(word, wordDict)) {
                string rem = s.substr(0, i);
                vector<string> prev = combine(word, wordBreak(rem, wordDict));
                result.insert(result.end(), prev.begin(), prev.end());
            }
        }
        m[s] = result; //memorize
        return result;
    }
};
### CSS `word-break` 属性详解 #### 定义与作用 `word-break` 是一个用于控制单词内断行行为的 CSS 属性。该属性定义了如何处理过长而不适合其容器宽度的文字,以及在何种情况下允许这些文字被拆分到多行显示。 #### 可选值及其效果 - **normal**: 使用默认规则来决定在哪里可以折行。通常只会在空格处或连字符上换行[^1]。 - **break-all**: 允许在任何字符间断开,即使是在非空白字符之间也会强制换行。这种设置对于包含大量不可分割长词的语言(如中文、日文)特别有用[^2]。 - **keep-all**: 防止除字典定义外的地方发生断裂;适用于不允许随意切割词语的情况,比如英文中的专有名词等[^3]. #### 实际应用案例 当页面布局中有固定大小但可能容纳不下某些较长文本内容时,可以通过调整此样式属性使溢出部分合理地分布于下一行而不是超出边界造成视觉混乱: ```html <div style="width: 200px; border: solid;"> <!-- 这里放置一段很长且无自然间隔符的日语字符串 --> </div> ``` 为了确保上述 HTML 中的内容能够在指定宽度范围内正确展示而不会破坏整体设计美感,则可以在对应的 `<style>` 或外部样式表文件中加入如下声明: ```css /* 设置 div 的 word-break 行为 */ div { word-break: break-all; } ``` 这样就可以让那些超宽却不含合法打断位置的文字也能按照预期表现出来,既不破坏原有结构又实现了良好的用户体验[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值