LeetCode139: Word Break
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 ".
I remember that I opened this question when I first made dynamic planning, but there was no idea at that time. Now I have made a lot of questions about dynamic planning. When I started this question today, I quickly came up with the State and State Transition equations. I can't say that I am still making some progress.
Define A [I] to indicate whether A subcharacter 0 to subscript I can be divided into multiple words in dict.
Then A [I] And A [j], 0 <= j <I are related, that is, A [I] and before A [] in the I-1 items are related, specifically:
If A [0] is 1, judge whether the subscripts starting from 1 to the end of I in s are in dict. If yes, set A [I] to 1 and jump out, otherwise, go to step 2. If A [1] is 1, judge whether the subscripts in s start from 2 to end with I are in dict, set A [I] to 1 and jump out. Otherwise, go to step 2;
.....
This keeps traversing to A [I-1] position.
In the previous traversal process, if j is traversed to A certain step, A [j] = 1 and the string represented by j + 1 to I appears in dict, it indicates that the first j strings can be divided into words in dict, And the strings in j + 1 to I can also be divided into words in dict, this means that the first I character can be split into words in dict.
When writing code, j can start traversing from I, which can reduce the number of traversal times.
Runtime: 4 ms
class Solution {public: bool wordBreak(string s, unordered_set
& wordDict) { int length=s.size(); int *A=new int[length](); for(int i=0;i
=0;j--) { if(j==i) { A[i]=isExist(s,0,i,wordDict); } else if(A[j]==1) { A[i]=isExist(s,j+1,i,wordDict); } if(A[i]==1) break; } } return A[length-1]==1; } int isExist(string &s,int first,int last,unordered_set
&wordDict) { string str=s.substr(first,last-first+1); if(wordDict.count(str)) return 1; else return 0; }};