博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
139. Word Break (DP)
阅读量:4073 次
发布时间:2019-05-25

本文共 1640 字,大约阅读时间需要 5 分钟。

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: trueExplanation: Return true because "leetcode" can be segmented as "leet code"

分析:注意超时问题

1. 动态规划问题,R[I]=R[0,J] && R[J,I] &&R[I,END]. 

public boolean wordBreak(String s, List
wordDict) { boolean[] match = new boolean[s.length()+1];//注意长度比s大1,因为substring是左闭右开 match[0] = true;//默认第一个是true才能开始循环 for(int i=1;i<=s.length();i++){ for(int j=0;j

2. 递归 利用string 的startswith 方法

/**     * 搜索字符串是否可以被分割成单词串     *     * @param s       字符串     * @param idx     处理的开始位置     * @param wordMap 单词字典,开始字符相同的在同一个set集合中     * @return 搜索结果     */    public boolean wordBreak(String s, int idx, Map
> wordMap) { if (idx >= s.length()) { return true; } Set
words = wordMap.get(s.charAt(idx)); if (words != null) { for (String word : words) { // idx之前的字符已经匹配,如果从ide之后起匹配word单词 if (s.startsWith(word, idx)) { // 递归处理 boolean result = wordBreak(s, idx + word.length(), wordMap); // 如果满足条件,返回true if (result) { return true; } } } } return false; }

参考

转载地址:http://infni.baihongyu.com/

你可能感兴趣的文章
头文件里一般会加入的宏定义,为了避免一个头文件被重复调用
查看>>
我感觉很有必要多刷刷leetcode
查看>>
关于单链表排序,倒置的具体方法(华清的方法,比我的好些)
查看>>
C语言计算数组长度时注意事项
查看>>
Vi复制一整行和复制多行
查看>>
快速排序qsort函数的compar参数
查看>>
应该至少掌握一门高级语言JAVA或C++
查看>>
我觉得你学编程或者找工作也可以用考研数学这种思想,做一百张卷子。
查看>>
选取的学习资料越难,学习效率越高。
查看>>
结构体嵌套结构体
查看>>
标准IO与文件IO的区别
查看>>
输出错误信息时,你不写课本上那样的if判断是否出错好像也是可以的
查看>>
就去把一本书啃烂
查看>>
linux API种类
查看>>
Linux系统编程之管理目录与文件的stat函数组
查看>>
目录流
查看>>
文件流、目录流、文件描述符总结
查看>>
Linux应用开发自学之路(转载)
查看>>
找工作准备的方向(4月22日写的)
查看>>
关于fwrite写入文件后打开查看是乱码的问题
查看>>