【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】

【139-Word Break(单词拆分)】


【LeetCode-面试算法经典-Java实现】【全部题目文件夹索引】

原题

  Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

  For example, given

  s = "leetcode",

  dict = ["leet", "code"].

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

题目大意

  给定一个字符串s和单词字典dict,确定s能否够切割成一个或多个单词空格分隔的序列。

解题思路

  一个字符串S,它的长度为N。假设S能够被“字典集合”(dict)中的单词拼接而成,那么所要满足的条件为:

* F(0, N) = F(0, i) && F(i, j) && F(j, N);

* 这样子,假设我们想知道某个子串是否可由Dict中的几个单词拼接而成就能够用这种方式得到结果(满足条件为True, 不满足条件为False)存入到一个boolean数组的相应位置上,这样子,最后boolean 数组的最后一位就是F(0, N)的值,为True表示这个字符串S可由Dict中的单词拼接,否则不行!

代码实现

算法实现类

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {

    public boolean wordBreak(String s, Set<String> wordDict) {
        // 參数校验
        if (s == null || s.length() < 1 || wordDict == null || wordDict.size() < 1) {
            return false;
        }

        // 标记是否匹配,match[i]表表[0, i-1]都匹配
        int length = s.length();
        boolean[] match = new boolean[length + 1];
        match[0] = true;

        for (int i = 1; i < length + 1; i++) {
            for (int j = 0; j < i; j++) {
                if (match[j] && wordDict.contains(s.substring(j, i))) {
                    // f(0,n) = f(0,i) + f(i,j) + f(j,n)
                    match[i] = true;
                    break;
                }
            }
        }

        return match[length];
    }

    // 以下是还有一种解法。可是会超时
    public boolean wordBreak2(String s, Set<String> wordDict) {

        // 參数校验
        if (s == null || s.length() < 1 || wordDict == null || wordDict.size() < 1) {
            return false;
        }

        Map<Character, Set<String>> wordMap = new HashMap<>(wordDict.size());
        // 将全部開始字符同样的单词放入一个Set中
        for (String word : wordDict) {
            Set<String> set = wordMap.get(word.charAt(0));
            if (set == null) {
                // 新创建一个set放入Map中
                set = new HashSet<>();
                wordMap.put(word.charAt(0), set);
            }
            // 单词存入set中
            set.add(word);
        }

        return wordBreak(s, 0, wordMap);
    }

    /**
     * 搜索字符串能否够被切割成单词串
     *
     * @param s       字符串
     * @param idx     处理的開始位置
     * @param wordMap 单词字典,開始字符同样的在同一个set集合中
     * @return 搜索结果
     */
    public boolean wordBreak(String s, int idx, Map<Character, Set<String>> wordMap) {

        if (idx >= s.length()) {
            return true;
        }

        Set<String> 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://blog.csdn.net/derrantcm/article/details/47774547

时间: 2024-10-26 14:44:32

【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】的相关文章

【LeetCode-面试算法经典-Java实现】【058-Length of Last Word (最后一个单词的长度)】

[058-Length of Last Word (最后一个单词的长度)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return

【LeetCode-面试算法经典-Java实现】【152-Reverse Words in a String(反转字符串中的单词)】

[152-Reverse Words in a String(反转字符串中的单词)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". 题目大意 给定一个字符串,将其反转,其的字词不转 解题思路

【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】

[079-Word Search(单词搜索)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally

【LeetCode-面试算法经典-Java实现】【030-Substring with Concatenation of All Words(串联所有单词的子串)】

[030-Substring with Concatenation of All Words(串联所有单词的子串)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concaten

【LeetCode-面试算法经典-Java实现】【030-Substring with Concatenation of All Words(串联全部单词的子串)】

[030-Substring with Concatenation of All Words(串联全部单词的子串)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concate

【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】

[107-Binary Tree Level Order Traversal II(二叉树层序遍历II)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example

【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】

[064-Minimum Path Sum(最小路径和)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either

【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】

[056-Merge Intervals(区间合并)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. 题目大意 给定一个区间集合,合并有重叠的区间. 解题思路 先对区间进行排序.按開始

【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】

[066-Plus One(加一)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 题目大意 给定一个用数组表示的一个数,