zoukankan      html  css  js  c++  java
  • 【LeetCode】139

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

    Solution:  

    dppos[i]==true/false表示字符串从开头到i的子串是否存在cut方案满足条件

    动态规划设置初值bpos[0]==true

    string.substr(int beginIndex, int length): 取string从beginIndex开始长length的子串

     1 class Solution {
     2 public:
     3     bool wordBreak(string s, unordered_set<string>& wordDict) {    //runtime:4ms
     4         vector<bool> dppos(s.size()+1, false);
     5         dppos[0]=true;
     6         
     7         for(int i=1;i<dppos.size();i++){
     8             for(int j=i-1;j>=0;j--){  //从右到左找快很多
     9                 
    10                 if(dppos[j]==true && wordDict.find(s.substr(j,i-j))!=wordDict.end()){  
    11                     dppos[i]=true;
    12                     break;   //只要找到一种切分方式就说明长度为i的单词可以成功切分,因此可以跳出内层循环
    13                 }
    14             }
    15         }
    16         return dppos[s.size()];
    17     }
    18 };
  • 相关阅读:
    PHP AES256加密算法
    PHP字符串比较
    linux常用命令
    播放音乐方法(兼容IE FF Chrome Opera Safari)
    JS小游戏象棋暗棋
    Sublime Text 2 介紹
    php生成QRcode
    几种极其隐蔽的XSS注入的防护
    JS判断碰撞方法
    php 发送带附件邮件
  • 原文地址:https://www.cnblogs.com/irun/p/4722705.html
Copyright © 2011-2022 走看看