zoukankan      html  css  js  c++  java
  • [LeetCode] 139. Word Break

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    Note:

    • The same word in the dictionary may be reused multiple times in the segmentation.
    • You may assume the dictionary does not contain duplicate words.

    Example 1:

    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation: Return true because "leetcode" can be segmented as "leet code".
    

    Example 2:

    Input: s = "applepenapple", wordDict = ["apple", "pen"]
    Output: true
    Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
                 Note that you are allowed to reuse a dictionary word.
    

    Example 3:

    Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    Output: false

    题意,给一个字符串,给一个字符串数组,问字符数组能否组装出字符串
    我佛了,这题,先说几个注意的地方,字符数组里的元素是可以重复使用的,字符数组里的元素是可以有剩余的
    一开始自信满满的用set直接解,每个元素直接扫,被“aaaaaaa”,【“aaa”,“aaaa”】 卡死了
    最后看了别人的博客才恍然大悟,挖槽,原来是到DP题
    真的是醉了,LeetCode上DP题型实在是难受
    关键在于拆的地方,直接上代码
    class Solution {
        public boolean wordBreak(String s, List<String> wordDict) {
            HashSet<String> set = new HashSet<>();
            for (int i = 0; i < wordDict.size(); i++) {
                set.add(wordDict.get(i));
            }
            boolean[] dp = new boolean[s.length() + 1];
            dp[0] = true;
            for (int i = 1; i < s.length() + 1; i++) {
                for (int j = 0; j < i; j++) {
                    if (dp[j] && set.contains(s.substring(j, i))) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            return dp[s.length()];
        }
    }
  • 相关阅读:
    CodeForces 705A(训练水题)
    --hdu 2602 Bone Collector (01背包)
    --Dirring love 音乐(01背包问题)
    简单的网络拓扑
    --hdu 1231 最大连续子序列(动态规划)
    hdu 1003 Max Sum(动态规划)
    hdu 1284 钱币兑换问题(动态规划)
    hdu 1176 免费馅饼(动态规划)
    hdu 2084 数塔(动态规划)
    --hdu 2124 Repair the Wall(贪心)
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9664978.html
Copyright © 2011-2022 走看看