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()];
        }
    }
  • 相关阅读:
    面试常见问题汇总
    java static变量及函数
    java自定义注解及其信息提取
    testNG 注释实例
    让我欲罢不能的node.js
    利用html 5 websocket做个山寨版web聊天室(手写C#服务器)
    html5 Web Workers
    html5 postMessage解决跨域、跨窗口消息传递
    C# socket编程实践——支持广播的简单socket服务器
    简单理解Socket
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9664978.html
Copyright © 2011-2022 走看看