zoukankan      html  css  js  c++  java
  • 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".

    这题拿到就开始硬做。。是不对滴。用DP做怎样?搞清楚state,function,initialize和result。

     1 public boolean wordBreak(String s, Set<String> dict) {
     2         int maxWordLen = 0;
     3         for (String str : dict) {
     4             maxWordLen = Math.max(maxWordLen, str.length());
     5         }
     6         //F[i] 代表在i时,前面的是否可以被字典中的词拆分
     7         //F[i] = (F[j] && dict.contains(s.substring(j ,i)))
     8         //F[0] = true;
     9         //return F[s.length()]
    10         boolean[] F = new boolean[s.length() + 1];
    11         F[0] = true;
    12         for (int i = 1; i <= s.length(); i++) {
    13             F[i] = false;
    14             for (int j = 0; j < i && j <= maxWordLen; j++) {
    15                 if (F[i - j - 1] && dict.contains(s.substring(i - j - 1, i))){
    16                     F[i] = true;
    17                 }
    18             }
    19         }
    20         return F[s.length()];
    21     }
  • 相关阅读:
    HashMap源码分析
    LinkedList源码分析
    ArrayList源码学习
    Java容器知识总结
    Collections 工具类和 Arrays 工具类常见方法
    Java基础知识
    MySQL高级之索引优化分析
    MySQL命令大全
    Java IO
    SpringCloud笔记
  • 原文地址:https://www.cnblogs.com/gonuts/p/4413402.html
Copyright © 2011-2022 走看看