Leetcode brush java problem of 139. Split words

Results of the:

by

Show details

When execution: 5 ms, beat the 83.83% of all users to submit in Java

Memory consumption: 36.4 MB, defeated 35.99% of all users to submit in Java

topic:

Given a string s non-empty and non-empty dictionary wordDict comprising a word list, it is determined whether the space s can be split into one or more words appear in the dictionary.

Description:


    Word in the dictionary can be reused when the split.
    You can assume that there is no repetition of the word in the dictionary.


Example 1:

Input: s = "leetcode", wordDict = [ "leet", "code"]
Output: true
interpretation: returns true because "leetcode" can be split into "leet code".


Example 2:

Input: s = "applepenapple", wordDict = [ "apple", "pen"]
Output: true
interpretation: returns true because "applepenapple" can be split into "apple pen apple".
     Note that you can re-use the word in the dictionary.


Example 3:

输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/word-break
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Ideas:

Establishing a string of the same length reachability booleaan array, then jump according to the dictionary, if you can jump from the previous position to the current position, it is set to true, finally, look at the last value of the boolean array, if ture , it can be split, false, it will not be split.

Code:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        //其实这个数组按照字典表达了一个可达性的问题
        //只能按照字典中的单词往后跳跃,如果可以跳跃到这个位置
        //那么就置为true
        //最后看最后一个位置,如果为false,说明不能跳到最后这个位置
        boolean[] result=new boolean[n+1];
        result[0]=true;
        for(int i=1;i<=n;i++)
        {
            //这个地方我当时考虑到为什么不用一个标志,而是每次都是从头
            //是考虑到这样一个问题
            //比如dogsand,其中字典中有sand和and,如果不是每次都是从头,那么就仅仅检测到
            //sand而没有and
            for(int j=0;j<i;j++)
            {
                if(result[j]&&wordDict.contains(s.substring(j,i)))
                {
                    result[i]=true;
                    break;
                }
            }
        }
        return result[n];

    }
}

 

Published 415 original articles · won praise 434 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_41901915/article/details/104104605