LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Given a stringSAnd a dictionary of wordsDict, Determine ifSCan 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 ".

[Idea]

At the beginning, I tried to match the problem as much as possible, for example, s = "abcdefabc" dict = ["abc ", "def"] I only need to remove all words in s that exist in the dictionary. Finally, if s does not have any letters, it means it can be break;

But the problem arises. s = "aaaaaaa" dict = ["aaa", "aaaa"]. In this case, aaa is directly used to divide s into aaa, aaa, and; returns false.

For example, s = "abcdeefg" dict = ["AB", "cde", "ee", "cd", "fg"], when "cde" in the dictionary is used for segmentation, the result is AB, cde, e, fg; and false is returned.

[Dynamic Planning and problem solving]

[Key Points★★]

Starting from s [2] = c, we found that two dictionary words match, that is, cde, cd, weMark the length they can splice

AB cdeefg

AB

Cde

Cd

---> Next, we will start matching from the position of efg or eefg.

 

[Code]
 1 public class Solution { 2     public boolean wordBreak(String s, Set<String> dict) { 3         boolean[] t = new boolean[s.length()+1]; 4         t[0] = true; //set first to be true, why? 5         //Because we need initial state 6   7         for(int i=0; i<s.length(); i++){ 8             //should continue from match position 9             if(!t[i]) 10                 continue;11  12             for(String a: dict){13                 int len = a.length();14                 int end = i + len;15                 if(end > s.length())16                     continue;17  18                 if(t[end]) continue;19  20                 if(s.substring(i, end).equals(a)){21                     t[end] = true;22                 }23             }24         }25  26         return t[s.length()];27     }28 }

 

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.