The idea is this. We start from the first character and look backwards, until we find a place where we can get the substring in dict, if we find the last one. Then it's false.
After finding the first one, find the next segmentation, of course, from the first segment of the next character start to find a continuous substring, but at this point and the first is slightly different. Let's say word= ' ab ', dict={' a ', AB ', ...}, after finding a, the next process is B. We found that B was not in dict, but we found that B could be combined with a to form AB and AB in Dict. So there are three options for each of these substrings. Either alone as an individual to the dict, or with the previous combination to find. Or just wait, wait for the new character. To form a longer substring.
But there's still a problem, and we're talking about finding it together with the front. So what's the definition of this front? Beginning? The first one after the beginning? The second one? So we're going to record some information. To represent the preceding substring, from where it was disconnected, thus satisfying the condition. Then we can combine the parts that are close to the current substring in turn. For example: Word = ' AaB ', dict = {A, aab}. When processing a. Is satisfying, the next a. is also satisfied, handling B, B is not in the dict, then a combination with the previous, the formation of AB, found not in the dict, then continue with the previous combination, the formation of AAB, hair now dict, then word overall meet the conditions.
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvc2hpcxv4aw5rb25n/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">
Class solution: # @param s, a string # @param dict, a set of string # @return A Boolean def wordbreak (self , S, dict): If Len (s) = = 0 or len (dict) = = 0: return False #初始长度为0, indicates that the previous element has been taken care of, and can proceed from 0 to the back DP = [0]
# s string, [1, Len (s)]. We're going to take care of each other . For I in range (1, Len (s) + 1): #前面全部的合法的断句处, which is the full legal starting point, because if the front is not done. Cannot proceed to the back of for J in Xrange (Len (DP)-1,-1,-1): substr = s[dp[j]: i] if substr in Dict: dp.append (i ) break return dp[-1] = = Len (s)
"Leetcode" Word Break (Python)