leetcode139-Word Break

题目

给你一个字符串 s 和一个字符串列表 wordDict 作为字典。如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = “leetcode”, wordDict = [“leet”, “code”]
输出: true
解释: 返回 true 因为 “leetcode” 可以由 “leet” 和 “code” 拼接成。

分析

这道题目用贪心肯定不行,因为字符串有多种拆分的方式,所以肯定是需要用动态规划解的,题目说如果在字典中都能找到的返回true,那么我们就用dp[i]数组来表示 从0到i的字符串是否可拆分,最终返回dp的最后一个元素即是最终的答案,而0~i可以分为0j和ji,如果dp[j]是可以拆分的同时S[i,j]子串也在字典中存在那么dp[i]肯定可以拆分,注意只要能找到一个字串能满足拆分需求的那就说明位置i处是可以拆分的

import java.util.List;
import java.util.ArrayList;

public class wordBreak {
	public static void main(String[] args) {
		String s = "leetcode";
		List<String> lis = new ArrayList();
		lis.add("leet");
		lis.add("code");
		System.out.println(wordBreak(s,lis));
	}

	public static boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;
        for(int i = 0;i<dp.length;i++) {
            for(int j = 0;j<i;j++) {
		System.out.println(j + "  " + i + "  " + s.substring(j,i) + " " + dp[j]);
                if(dp[j] && wordDict.contains(s.substring(j,i))) {
		System.out.println("++++++" + s.substring(j,i));
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[dp.length-1];
    }
}

相关推荐

  1. leetcode139-Word Break

    2024-06-19 09:00:07       29 阅读
  2. Leetcode 169

    2024-06-19 09:00:07       43 阅读
  3. 贪心算法03(leetcode1005,134,135

    2024-06-19 09:00:07       36 阅读
  4. Leetcode 139 单词拆分

    2024-06-19 09:00:07       54 阅读
  5. leetcode 139. 单词拆分

    2024-06-19 09:00:07       38 阅读
  6. LeetCode 139. 单词拆分

    2024-06-19 09:00:07       37 阅读
  7. LeetCode-134】加油站(贪心)

    2024-06-19 09:00:07       54 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-19 09:00:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-19 09:00:07       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-19 09:00:07       82 阅读
  4. Python语言-面向对象

    2024-06-19 09:00:07       91 阅读

热门阅读

  1. Angular 2 数据显示

    2024-06-19 09:00:07       65 阅读
  2. 新手怎么使用GitLab?

    2024-06-19 09:00:07       36 阅读
  3. word常用的通配符大全

    2024-06-19 09:00:07       69 阅读
  4. Mellanox&nvidia ib高速网络异常排查FAQ

    2024-06-19 09:00:07       30 阅读
  5. Ubuntu 查看设备温度

    2024-06-19 09:00:07       30 阅读
  6. 5、分支对比 - 课件

    2024-06-19 09:00:07       31 阅读
  7. Python----多线程使用

    2024-06-19 09:00:07       29 阅读
  8. 234. 回文链表

    2024-06-19 09:00:07       33 阅读
  9. 组帧的方法

    2024-06-19 09:00:07       31 阅读