• leetcode139.单词拆分


    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

    思路分析:

    (1)比较容易想到的解法是,从字符串 s 开头处开始匹配,若匹配到字典里的字符串,则继续匹配剩下的字符串。这样递归下去,直到找到一个可行的序列或尝试所有的单词组合。

    提交的时候发现算法超时,后来想想其实这种解法存在很大的冗余,比如同时存在 a, b, ab的字典。只需记录下字符串 s 中的序列可以被字典匹配到即可,其实就是动态规划的思想;

    (2)采用动态规划解法,新建一个数组记录下字符串 s 的子序列是否可以被字典拆分,依次求解字符串 s 从 0位置开始的的所有子序列是否可以被拆分。代码如下:

        bool wordBreak(string s, vector<string>& wordDict) {
            vector<bool> state(s.length()+1, false);
            state[0] = true;
            for (int i = 1; i <= s.length(); i++) {
                for (int j = 0; j <= i ; j++) {
                    if (state[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end()) {
                        state[i] = true;
                    }
                }
            }        
            return state[s.length()];
        }

    接下来继续解决单词拆分2:

    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

    思路分析:

    返回所有可能的句子,即得到所有的子序列,可以直接采用上述分析(1)的方法,递归遍历得到所有的可行子序列。代码如下:

    class Solution {
    public:
        vector<string> wordBreak(string s, vector<string>& wordDict) {
            vector<bool> state(s.length()+1, false);
            state[0] = true;

         //先判断字符串 s 中是否能找到可行的拆分方案,再递归找出所有子序列。
    for (int i = 1; i <= s.length(); i++) { for (int j = 0; j <= i ; j++) { if (state[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end()) { state[i] = true; } } }
        
    if (state[s.length()] == true) { string sentence; dfs(s, 0, sentence, wordDict); } return _sentences; } void dfs(string& s, int start, string& sentence, vector<string>& wordDict) { for (auto str : wordDict) { if (s.substr(start, str.size()) == str) { string nextSentence = sentence; if (nextSentence.length()) nextSentence.append(" "); nextSentence.append(str); int len = start + str.size(); if (len == s.size()) { _sentences.push_back(nextSentence); } else { dfs(s, len, nextSentence, wordDict); } } } } private: vector<string> _sentences; };
  • 相关阅读:
    Math类操作数据
    java之静态方法与非静态方法
    使用Date和SimpleDateFormat类表示时间
    Java 中基本类型和字符串之间的转换
    Python基础
    生成对抗网络
    机器翻译
    语义角色标注
    个性化推荐
    词向量
  • 原文地址:https://www.cnblogs.com/hanawasakuraki/p/9536881.html
Copyright © 2020-2023  润新知