Leetcode--Word break dynamic planning, detailed understanding

Source: Internet
Author: User

Given A string s and a Dictionary of words dict, determine if s can segmented into a spa Ce-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".

Ideas

The first thing I did with that question was to match as much as possible, for example s = "ABCDEFABC" dict=["abc", "Def", and I just took out all the words in the dictionary in S, Finally, if s does not have any letters then it can break;

But the problem comes, s= "aaaaaaa" dict=["AAA", "AAAA", this time will be directly using AAA to divide s into Aaa,aaa,a, thus returning false.

For example, s= "ABCDEEFG" dict=["AB", "CDE", "ee", "CD", "FG", when used in the dictionary "CDE" to split, the result is AB, CDE, E, FG; Thus returning false.

"Dynamic Programming Problem solving"

"Key ★"

Starting with S[2]=c, we've found two dictionary words to match, namely: CDE,CD, we mark the lengths they can stitch together.

ab CDEEFG

AB

Cde

CD

---> Next, we'll start with the location of EFG or EEFG.

"Code"
1  Public classSolution {2      Public BooleanWordbreak (String s, set<string>dict) {3         Boolean[] t =New Boolean[S.length () +1];4T[0] =true;//set first to is true, why?5         //Because We need initial state6  7          for(inti=0; I<s.length (); i++){8             //should continue from match position9             if(!T[i])Ten                 Continue; One   A              for(String a:dict) { -                 intLen =a.length (); -                 intend = i +Len; the                 if(End >s.length ()) -                     Continue; -   -                 if(T[end])Continue; +   -                 if(S.substring (i, End). Equals (a)) { +T[end] =true; A                 } at             } -         } -   -         returnt[s.length ()]; -     } -}

Leetcode--Word break dynamic planning, detailed understanding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.