• LintCode-Word Segmentation


    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.

    Example

    Given

    s = "lintcode",

    dict = ["lint", "code"].

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

    Analysis:

    It is a DP problem. However, we need to use charAt() instead of substring() to optimize speed. Also, we can first check whether each char in s has appeared in dict, if not, then directly return false. (This is used to pass the last test case in LintCode).

    Solution:

     1 public class Solution {
     2     /**
     3      * @param s: A string s
     4      * @param dict: A dictionary of words dict
     5      */
     6     public boolean wordSegmentation(String s, Set<String> dict) {
     7         if (s.length()==0) return true;
     8         
     9         char[] chars = new char[256];
    10         for (String word : dict)
    11             for (int i=0;i<word.length();i++)
    12                 chars[word.charAt(i)]++;
    13 
    14         for (int i = 0;i<s.length();i++)
    15             if (chars[s.charAt(i)]==0) return false;
    16 
    17         boolean[] d = new boolean[s.length()+1];
    18         Arrays.fill(d,false);
    19         d[0] = true;
    20         for (int i=1;i<=s.length();i++){
    21         StringBuilder builder = new StringBuilder();
    22             for (int j=i-1;j>=0;j--){
    23                 builder.insert(0,s.charAt(j));
    24                 String cur = builder.toString();
    25                 if (d[j] && dict.contains(cur)){
    26                     d[i]=true;
    27                     break;
    28                 }
    29             }
    30         }
    31 
    32         return d[s.length()];
    33 
    34     }
    35 }
  • 相关阅读:
    代理
    博客园主题
    JS_1
    脚本语言
    Hadoop生态体系
    Hadoop序列化程序报错
    46. 全排列
    1038 Recover the Smallest Number (30分)
    1064 Complete Binary Search Tree (30分)
    1034 Head of a Gang (30分)
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4183748.html
Copyright © 2020-2023  润新知