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;
        }
    };
  • 相关阅读:
    物理机连接虚拟机中的sqlserver
    Vue.js
    拆分时间段
    System.Threading.Timer
    浏览器被恶心页面占用
    sqlserver超时时间已到
    几年没写CSS
    C#生成高清缩略图
    抽奖概率算法
    html 页面实现指定位置的跳转
  • 原文地址:https://www.cnblogs.com/ballwql/p/3708022.html
Copyright © 2011-2022 走看看