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".

     1 public class Solution {
     2     public boolean wordBreak(String s, Set<String> dict) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(s == null || s.length() == 0) return true;
     5         int len = s.length();
     6         boolean[] map = new boolean[len];
     7         for(int i = len - 1; i > -1; i --){
     8             for(int j = i + 1; j <= len; j ++){
     9                 String ss = s.substring(i,j);
    10                 if(dict.contains(ss) && j == len){
    11                     map[i] = true;
    12                     break;
    13                 }
    14                 else if(dict.contains(ss) && j < len && map[j] == true){
    15                     map[i] = true;
    16                     break;
    17                 }
    18             }
    19         }
    20         return map[0];
    21     }
    22 }

     第二遍:

     1 public class Solution {
     2     public boolean wordBreak(String s, Set<String> dict) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(s == null || s.length() == 0) return true;
     5         int len = s.length();
     6         boolean[] map = new boolean[len];
     7         for(int i = len - 1; i > -1; i --)
     8             for(int j = i + 1; j <= len; j ++){
     9                     if(j < len && !map[j]) continue;
    10                     else if(dict.contains(s.substring(i, j)) && (j == len || map[j])){
    11                         map[i] = true;
    12                         break;
    13                     }
    14         }
    15         return map[0];
    16     }
    17 }
  • 相关阅读:
    Python 基础 (三)
    Python 基础(二)
    软件工程第四周作业
    软件工程第四周作业
    软件工程第四次作业
    软件工程第四周作业
    软件工程第三次作业
    软件工程第三周作业
    软件工程第三次作业
    Python学习之路5
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3358837.html
Copyright © 2011-2022 走看看