zoukankan      html  css  js  c++  java
  • 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()];
        }
    };
  • 相关阅读:
    CF767C Garland
    P2458 [SDOI2006]保安站岗
    P2704 [NOI2001]炮兵阵地
    P2607 [ZJOI2008]骑士
    POJ 1201 Interval (查分约束系统)
    位运算的魅力---N皇后问题
    设计模式之代理模式20170724
    C之Volatile关键字的介绍与使用20170724
    设计模式之桥梁模式20170721
    设计模式之策略模式20170720
  • 原文地址:https://www.cnblogs.com/yeek/p/3575184.html
Copyright © 2011-2022 走看看