• 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 }
  • 相关阅读:
    .NET 高效开发之不可错过的实用工具(第一的当然是ReSharper插件)
    灵活运用 SQL SERVER FOR XML PATH 转
    Python 3.X 要使用urllib.request 来抓取网络资源。转
    22-1 拖拽与烟花案例
    21、bootstrap框架
    20、promise与ajax jsonp
    18、MySQL
    19、AJAX
    17、php
    16-1 ECMA5与ECMA6的函数定义
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3358837.html
Copyright © 2020-2023  润新知