• LeetCode139:Word Break


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

    记得最開始做动态规划的题时是打开过这道题的,可是那时没什么思路。如今动态规划的题刷了不少了,今天再做这道题时非常快就想出了状态和状态转移方程。不能不说还是有点进步。


    定义A[i]表示0到下标为i的子字符是否能被切割成dict中的多个单词。
    那么A[i]与A[j],0<=j< i都有关系,即A[i]与前A[]中的前i-1项都有关系,详细为:

    1. 假设A[0]为1。推断s中下标从1開始到i结束的字符是否在dict中,假设在,设置A[i]为1,跳出。否则进入第二步。
    2. 假设A[1]为1,推断s中下标从2開始到i结束的字符是否在dict中。假设在。设置A[i]为1,跳出,否则进入第二步;
      …..
      这样一直遍历到A[i-1]位置。


      在上面的遍历过程中假设遍历到某一步j,A[j]=1而且j+1到i表示的字符串出如今dict中,表示前j个字符串能切割成dict中的单词,j+1到i中的字符串串也能切割成dict中的单词。这样表示前i个字符能被切割成dict中的单词。

    实际编写代码时,j能够从i開始倒着開始遍历,这样能够降低遍历的次数。

    runtime:4ms

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string>& wordDict) {
            int length=s.size();
            int *A=new int[length]();
            for(int i=0;i<length;i++)
            {
                for(int j=i;j>=0;j--)
                {
                    if(j==i)
                    {
                        A[i]=isExist(s,0,i,wordDict);
                    }
                    else if(A[j]==1)
                    {
                        A[i]=isExist(s,j+1,i,wordDict);
                    }
                    if(A[i]==1)
                            break;
                }
            }
    
            return A[length-1]==1;
    
        }
    
            int isExist(string &s,int first,int last,unordered_set<string> &wordDict)
            {
                string str=s.substr(first,last-first+1);
                if(wordDict.count(str))
                    return 1;
                else
                    return 0;
            }
    
    };
  • 相关阅读:
    频率组件
    Django-admin组件
    Python全栈开发课堂笔记_day03
    python全栈开发day02
    python全栈开发day01
    正确认知自己,做真实的自己
    翻出大学时期收集的文章来看看
    mybatis中的#{}和${}
    Parameter index out of range (2 > number of parameters, which is 1)
    中间件
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/7197159.html
Copyright © 2020-2023  润新知