leetcode 139. Word Break

这道题用动态规划解决。

cpp 复制代码
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet;
        for(string& word:wordDict){
            wordSet.insert(word);
        }
        int s_len = s.size();
        //s的下标从1开始起算,dp[j]表示s[1,j]能拆分成wordDict的组合
        vector<bool> dp(s_len+1,false);
        dp[0] = true;//表示空串

        for(int len = 1;len <= s_len;len++){//对s[1,len]遍历
            for(int i = 0;i < len;i++){//对s[1,len]的拆分点遍历
                if(dp[i] && wordSet.find(s.substr(i,len-i)) != wordSet.end()){
                    dp[len] = true;
                    break;
                }
            }
        }
        return dp[s_len];
    }
};

可以事先确定,wordDict中最长的单词的长度max_word_len。这样在考虑s.sub(i,len-i)时候,如果len-i大于max_word_len就可以直接跳过这种情况。

优化后的代码:

cpp 复制代码
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet;
        int max_word_len = 0;
        for(string& word:wordDict){
            wordSet.insert(word);
            if(word.size() > max_word_len) max_word_len = word.size();
        }
        int s_len = s.size();
        //s的下标从1开始起算,dp[j]表示s[1,j]能拆分成wordDict的组合
        vector<bool> dp(s_len+1,false);
        dp[0] = true;//表示空串

        for(int len = 1;len <= s_len;len++){//对s[1,len]遍历
            for(int i = 0;i < len;i++){//对s[1,len]的拆分点遍历
                if(len -i > max_word_len)
                    continue;
                if(dp[i] && wordSet.find(s.substr(i,len-i)) != wordSet.end()){
                    dp[len] = true;
                    break;
                }
            }
        }
        return dp[s_len];
    }
};
相关推荐
嘉陵妹妹1 小时前
深度优先算法学习
学习·算法·深度优先
空中湖1 小时前
免费批量Markdown转Word工具
word·markdown
GalaxyPokemon1 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
hn小菜鸡2 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX2 小时前
分享今天做的力扣SQL题
sql·算法·leetcode
music&movie3 小时前
算法工程师认知水平要求总结
人工智能·算法
呆萌的代Ma3 小时前
Cursor实现用excel数据填充word模版的方法
word·excel
laocui14 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910134 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥5 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表