• LeetCode 139. Word Break


    139. Word Break

    Description Submission Solutions

    • Total Accepted: 131482
    • Total Submissions: 457810
    • Difficulty: Medium
    • Contributors: Admin

    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".

    UPDATE (2017/1/4):
    The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

    Subscribe to see which companies asked this question.


    【题目分析】

    给定一个目标字符串和一个字符串列表,判断目标字符串是否能由字符串列表中的串组合而成。


    【思路】

    1. DP套路多,把大问题分解为子问题还是很考验难度的。

    2. 要认真分析,不要急躁。

    3. 要注意下标

    4. 在本问题中,判断一个大的字符串是否可以被组合成功,可以分解为s.substring(0,i)和substring(i, s.length()),(0=<i<s.length())是否存在一个i使得被分成两部分的字符串都可以被列表中的串组合成功。


    【java代码】

     1 public class Solution {
     2     public boolean wordBreak(String s, List<String> wordDict) {
     3         boolean[] flag = new boolean[s.length()+1];
     4         flag[0] = true;
     5         
     6         for(int i = 1; i <= s.length(); i++) {
     7             for(int j = i-1; j >= 0; j--) {
     8                 if(flag[j] && wordDict.contains(s.substring(j,i))) {
     9                     flag[i] = true;
    10                     break;
    11                 }
    12             }
    13         }
    14         
    15         return flag[s.length()];
    16     }
    17 }
  • 相关阅读:
    hdu 5352 匈牙利(多重匹配)
    hdu 2112 最短路+stl
    hdu 1811 拓扑排序+并查集+细心
    hdu5407 CRB and Candies
    hdu1018 Big Number
    hdu5410 CRB and His Birthday
    hdu1023 Train Problem II
    hdu4812 D Tree
    hdu1085 Holding Bin-Laden Captive!
    hdu4810 Wall Painting
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6479281.html
Copyright © 2020-2023  润新知