zoukankan      html  css  js  c++  java
  • LeetCode Word Break

    Problem Description

    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".

    Problem Solution:

    Note: 参照官网用的方法,DP可解决问题,即将源字符串从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程,代码如下:

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string> &dict) {
            int nsize=s.size();
            int i=0,j=0;
            bool *dp = new bool[nsize];
            memset(dp,false,sizeof(dp));
            
            for(i=0;i<nsize;++i)
            {
                dp[i] = ((dict.find(s.substr(0,i+1))!=dict.end())?true:false);
                if(dp[i])
                    continue;
                else
                {
                    for(j=0;j<i;++j)
                    {
                        if(dp[j])
                        {
                            dp[i] = ((dict.find(s.substr(j+1,i-j))!=dict.end())?true:false) | dp[i];
                        }
                    }
                }
            }
            return dp[nsize-1];
            delete []dp;
        }
    };
  • 相关阅读:
    5402.绝对差不超过限制的最长数组
    快乐数
    无重复字符的最长子串
    数组中数字出现的次数
    盛最多的水
    对角线遍历
    LeetCode第24场周赛
    CSS样式
    笔记
    开关电源设计
  • 原文地址:https://www.cnblogs.com/ballwql/p/3708022.html
Copyright © 2011-2022 走看看