[解题报告]word break

题目:

Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

Example

Given s = "lintcode", dict = ["lint", "code"].

Return true because "lintcode" can be break as "lint code".

思路:

用一个布尔数组canSeg[i]表示给定的string的前[i]个子串(即s.substring(0, i))是否可以被划分。

这里注意的是substring(beginIndex, endIndex)中,不包含endIndex的字符,所以canSeg的长度应该是string的长度+1。 第一次就wa在了这个上面。

所以状态方程是这样 canSeg[i] = true if (canSeg[j] == true && s.substring(j, i) in dict)。初始值设为 canSeg[0] = true

小优化:

本来两层for循环可以写为 for( int i = 1; i <= length; i++ ) for (j = 0; j < i; j++) 但是考虑到word的长度一般比较小,在string很长的时候,前面很多很多此的j循环其实是无效的,比如string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaba"; dict = ["a", "b"], 在i循环到最后时,大部分的j循环并不会改变canSeg[i]的值,因为substring太长了,远远超过maxWordLength,肯定不在在字典里。所以考虑只让j在每次最多循环maxWordLength次,即可以从后向前找。

本来答案没怎么看明白,小优化是自己睡觉的时候突然想到的。

public class Solution {
    /**
     * @param s: A string s
     * @param dict: A dictionary of words dict
     */
    //思路:F(x) = true if F(i) == true && string(i,x) in dict
    public int maxLengthWord(Set<String> dict) {
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        return maxLength;
    }
    public boolean wordBreak(String s, Set<String> dict) {
        // write your code here
        if (s == null || s.length() == 0) {
            return true;
        }

        int wordlen = maxLengthWord(dict);
        // canSeg[i] 代表i之前的部分能不能被分,不包括i
        boolean[] canSeg = new boolean[s.length() + 1];
        canSeg[0] = true;
        String word;
        for (int i = 1; i <= s.length(); i++) {
            for(int j = i; j >= 0 && i - j <= wordlen; j--) {
                word = s.substring(j, i);
                if (canSeg[j] && dict.contains(word)) {
                    canSeg[i] = true;
                    break;
                }
            }
        }

        return canSeg[s.length()];
    }
}
时间: 2024-10-07 13:04:53

[解题报告]word break的相关文章

【LeetCode】Word Break II 解题报告

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = "catsanddog", dict = ["cat", "cats&quo

LeetCode: Word Break II 解题报告

Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = "catsanddog", dict = ["cat",

ZOJ 3706 Break Standard Weight 解题报告

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5009 题目意思:给出两个mass:x 和 y,问如何将其中一个 mass 一分为二(当然分完之后它们的和要等于原来的mass,或x 或 y),使得利用这三个mass 可称的数量最大.输出这个最大数量. 网上参考别人用STL中的set来写,太厉害了!!!考虑到set对于重复的元素只存储一个,那么当三个mass组合的过程中有重复的,它都会自动舍弃有重复的,不需要用if来

【LeetCode】Word Search II 解题报告

[题目] Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The sa

[LeetCode] Word Break II 解题思路

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, givens = "catsanddog",dict = ["cat", "cats"

解题报告 之 POJ2175 Evacuation Plan

解题报告 之 POJ2175 Evacuation Plan Description The City has a number of municipal buildings and a number of fallout shelters that were build specially to hide municipal workers in case of a nuclear war. Each fallout shelter has a limited capacity in term

暑训day1解题报告

A - Painting the sticks 因为不能覆盖涂/涂两次,所以就数数有几个三个一块儿就行了. #include<cstdio> int a[100],ans ; int main() { int n , t = 0 ; while (scanf("%d",&n)!=EOF) { for (int i=1; i<=n; ++i) scanf("%d",a+i); ans = 0 ; for (int i=1; i<=n ;

解题报告 之 POJ3057 Evacuation

解题报告 之 POJ3057 Evacuation Description Fires can be disastrous, especially when a fire breaks out in a room that is completely filled with people. Rooms usually have a couple of exits and emergency exits, but with everyone rushing out at the same time

2016 第七届蓝桥杯 c/c++ B组省赛真题及解题报告

2016 第七届蓝桥杯 c/c++ B组省赛真题及解题报告 勘误1:第6题第4个 if最后一个条件粗心写错了,答案应为1580. 条件应为abs(a[3]-a[7])!=1,宝宝心理苦啊.!感谢zzh童鞋的提醒. 勘误2:第7题在推断连通的时候条件写错了,后两个if条件中是应该是<=12 落了一个等于号.正确答案应为116. 1.煤球数目 有一堆煤球.堆成三角棱锥形.详细: 第一层放1个, 第二层3个(排列成三角形), 第三层6个(排列成三角形), 第四层10个(排列成三角形). -. 假设一共