zoukankan      html  css  js  c++  java
  • [LeetCode] 139. Word Break Java

    题目:

    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. You may assume the dictionary does not contain duplicate words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code".

    题意及分析:给出一个字符串s和一个字典list,判断由字典中的单词能否组成字符串s。这道题可以用动态规划的思路求解,对于s的任意一个子字符串subString1=s.subString(0,i+1),如果该子字符串能够被字典中单词构成,那么只有一种情况,即有一个能被字典中单词构成的子字符串加上一个在字典中的单词,对字符串进行遍历即可。这里需要注意的是subString操作时左闭右开的。

    代码:

    public class Solution {
        public boolean wordBreak(String s, List<String> wordDict) {
            int length=s.length();
            boolean[] res=new boolean[length+1];	//记录到第0个字符到第i个字符的子字符串能否被字典划分
            res[0]=true;
            for(int i=1;i<=length;i++){     //s的每个子字符串求解   
            	for(int j=0;j<i;j++){
            		if(res[j]&&wordDict.contains(s.substring(j, i))){
            			res[i]=true;
            			break;
            		}
            	}
            }
            return res[length];
        }
    }
    

      

     

  • 相关阅读:
    dubbo官方文档笔记
    maven权威指南读书笔记
    ArrayList实现
    通过json把int[]转成Integer[]
    二分查找,希尔排序,欧几里得,斐波那契
    js快捷键设置
    java字符串和时间转换
    希尔排序动画
    vue render
    前端性能优化,算法
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6922675.html
Copyright © 2011-2022 走看看