[leetcode]139. Word Break单词能否拆分

本文介绍了一种判断字符串是否能由字典中的单词组合而成的算法。通过使用一维布尔数组记录字符串能否被正确分隔,并结合双层循环进行验证,有效地解决了这一问题。

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

 

题意:

给定字符串S和字典wordDict, 判断字符串S是否能由字典中的单词组合而成

 

思路:

用一维boolean数组记录是否能字符串S是否能被分隔

           l       e      e      t       c      o      d     e 

TFFFFFFFF
012345678

  dp[0]初始化为true, 其他为default的false

  dp[s.length() + 1]

 

i = 1         j = 1,  dp[1] 为default F, 没必要再去验证wordDict.contains(s.substring(j,i))

               j = 0,  dp[0] 为 T , 验证wordDict.contains(s.substring(0,1)) 为F

i = 2        j = 2,  dp[2] 为default F

              j = 1,  dp[1] 为default F

      j = 0,  dp[0] 为 T , 验证wordDict.contains(s.substring(0,2)) 为F

i = 3        j = 3,  dp[3] 为default F

              j = 2,  dp[2] 为default F

              j = 1,  dp[1] 为default F

      j = 0,  dp[0] 为 T , 验证wordDict.contains(s.substring(0,3)) 为F

i = 4       j = 4, dp[4]为default F

     j = 3,  dp[3] 为default F

              j = 2,  dp[2] 为default F

              j = 1,  dp[1] 为default F

      j = 0,  dp[0] 为 T , 验证wordDict.contains(s.substring(0,4)) 为T  ----> 更新dp[4] = true

TFFFTFFFF
012345678

 

 

              

 

 

代码:

 1 class Solution {
 2     public boolean wordBreak(String s, List<String> wordDict) {
 3         // corner case 
 4         if (s == null || s.length() < 1 || wordDict == null || wordDict.size() < 1) {
 5             return false;
 6         }  
 7         boolean[] dp = new boolean[s.length() + 1];
 8         dp[0] = true;
 9         //外层循环scan字符串S
10         for(int i = 1; i <= s.length(); i++ ){
11             //内层循环找分割点
12             for(int j = i; j >= 0; j--){
13                 if(dp[j] && wordDict.contains(s.substring(j,i))){
14                     dp[i] = true;
15                 }
16             }
17         }
18         return dp[s.length()];
19     }
20 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/9075032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值