zoukankan      html  css  js  c++  java
  • leetcode — word-break

    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * Source : https://oj.leetcode.com/problems/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 WordBreak {
    
        /**
         * 判断给定的字符串是否能分割为多个单词,每个单词都包含在给定的字典中
         *
         * 1. 使用DFS,如果能到达字符串最后,说明可以break
         * 2. 题目中只是判断是否的问题,并不需要求出具体break的方法,对于是否的问题可以使用DP来解决
         *
         * dp[i]:表示str[i-1]能否被break,比如dp[1]表示str[0:0]能否被break
         * dp[0] = true
         * dp[i] = true,当:
         * 存在0 <= k <= i-1, dp[k] = true, 并且tr[k:i-1] 存在dic中
         *
         * @param str
         * @param dic
         * @return
         */
        public boolean wordBreak (String str, Set<String> dic) {
            boolean[] dp = new boolean[str.length()+1];
            dp[0] = true;
            for (int i = 0; i < str.length(); i++) {
                for (int j = i; j > -1; j--) {
                    if (dp[j] && dic.contains(str.substring(j, i+1))) {
                        dp[i + 1] = true;
                        break;
                    }
                }
            }
            return dp[str.length()];
        }
    
    
        public static void main(String[] args) {
            WordBreak wordBreak = new WordBreak();
            String[] dicStr = new String[]{"leet", "code"};
            boolean result = wordBreak.wordBreak("leetcode", new HashSet<String>(Arrays.asList(dicStr)));
            System.out.println(result + " == true");
        }
    }
    
  • 相关阅读:
    strcpy ,strncpy ,strlcpy(转载)
    窗口刷新时的问题(转)
    Linux下的实时流媒体编程(RTP,RTCP,RTSP)
    YUV色彩空间(转自百度百科)
    VC++2005快速构建安全的应用程序
    Linux多线程编程
    C++ PASCAL关键字(转)
    SkinMagic 进行皮肤设置
    .h和.cpp文件的区别
    strcpy_s与strcpy安全性的比较(转载)
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7902539.html
Copyright © 2011-2022 走看看