LeetCode Word Break Problem Solving Report

Topic description

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".
Given a dictionary set and a string, determine whether the string can be segmented into one or more words in the dictionary set

Dynamic programming:
Dynamic programming is an algorithm idea. It uses space to store historical information so that it does not need to be recalculated when historical information is needed in the future, thereby reducing the time complexity. It is a method of exchanging space for time.

Three core elements:
optimal substructure, boundary, state transition equation

Ideas:

1. Since dynamic programming needs to store historical information, we should first confirm the historical information we want to store. Here I use boolean loca[i] to represent the i-th character of string s, whether it can be represented by words in dict.
2. Then, let's say we have the result of loca[0...i-1], then the value of loca[i] should be: loca[i] = loca[j] && s.substring(j, i + 1) in dict, where j belongs to [0...i - 1]. This is what we call the equation of state.

The optimal substructure is not required here, as long as the conditions are satisfied, and the optimal substructure is not required.
Boundary value set loca[0] = true
state transition equation: loca[i] = loca[j] &&s.substring(j,i+1) in dict

import java.util.*;
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        int len = s.length();
        boolean[] loca = new boolean[len+1];
        loca[0] = true;
        for(int i=1;i <= len;i++){
            for(int j = 0;j < i;j++){
                //前j-1个元素in dict且第j~i-1个元素构成的单词in dict,则判断loca[i] = true
                if(loca[j] && dict.contains(s.substring(j,i))){
                    loca[i] = true;
                    break;
                }
            }
        }
        return loca[len];
    }
}

Detailed explanation of dynamic programming algorithm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324836900&siteId=291194637