zoukankan      html  css  js  c++  java
  • (算法)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".

    思路:

    1、DFS

    2、动态规划

    代码:

    #include<iostream>
    #include<unordered_set>
    #include<vector>
    
    using namespace std;
    
    // dp
    bool WordBreak_dp(string s,unordered_set<string> &wordDict){
        int n=s.size();
    
        vector<bool> dp(n+1,false);
        dp[0]=true;
    
        for(int i=0;i<n;i++){
            for(int j=i;j>=0;j--){
                if(!dp[j]) continue;
                if(wordDict.find(s.substr(j,i-j+1))!=wordDict.end()){
                    dp[i+1]=true;
                    break;
                }
            }
        }
        return dp[n];
    
    }
    
    // dfs
    bool WordBreak_dfs(string s,unordered_set<string> &wordDict){
        if(s=="") 
            return true;
        for(int i=0;i<s.size();i++){
            if(wordDict.find(s.substr(0,i+1))!=wordDict.end()){
                if(WordBreak_dfs(s.substr(i+1),wordDict))
                    return true;
            }
        }
        return false;
    }
    
    int main(){
        unordered_set<string> wordDict;
        wordDict.insert("leet");
        wordDict.insert("code");
        string s;
        while(cin>>s){
            cout<< WordBreak_dp(s,wordDict) <<endl;
            cout<< WordBreak_dfs(s,wordDict) <<endl;
        }
        return 0;
    }
  • 相关阅读:
    Spark 分布式环境---slave节点无法启动(已解决)
    Hadoop 分布式环境slave节点重启忽然不好使了
    Spark 2.2.0 分布式集群环境搭建
    arm-linux-gcc
    VS+QT创建一个OpenCV应用
    QT安装和vs2015使用
    DE1_MSEL
    Hog实例
    resize函数
    Hog特征
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4896286.html
Copyright © 2011-2022 走看看