• LeetCode: 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".

    粗暴递归,结果超时

    public class Solution {
        public boolean wordBreak(String s, Set<String> dict) {
            if(s == null) return false;
            int start, end;
            start = end = 0;
            int length = s.length();
            while(start < length){
                     if( dict.contains(s.substring(0,start)) && wordBreak(s.substring(start+1),dict) ){
                         return true;
                     }else{
                         start++;
                     }
            }
            return false;
        }
    }
    

    Submission Result: Time Limit Exceeded ()

    Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]

    DP Solution:

    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string> &dict) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<bool> checked(s.length()+1, false);
            checked[0] = true;
            for (int i = 1; i <= s.length(); ++i) {
                for (int j = 0; j < i; ++j) {
                    if (checked[j] && dict.find(s.substr(j,i-j)) != dict.end()) {
                        checked[i] = true;
                        break;
                    }
                }
            }
            return checked[s.length()];
        }
    };
  • 相关阅读:
    NFS-网络文件共享服务
    CentOS7.5基础优化与常用配置
    29张截图-全新安装CentOS7.5-超详细!
    VMware跨电脑移动Linux虚拟机
    搭建markdown图床-腾讯云COS
    tcpdump-抓包工具-Linux
    vmware克隆虚拟机
    CentOS6.9安装httpd并正确配置静态IP地址
    区块链核心技术与应用
    docker安装jenkins自动化部署
  • 原文地址:https://www.cnblogs.com/yeek/p/3575184.html
Copyright © 2020-2023  润新知