Word break/word segment

Source: Internet
Author: User

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"leet code".

Dynamic Programming. Use a table to record 0 ~ Whether the I-1 meets the requirements. Note that the first table [0] = true, and the table length is the length of the input string plus one. Loop 0 ~ S. Length ()-1, which can only start from where Table [I] = true, because it is matched before it can be matched.

public class Solution {    public boolean wordBreak(String s, Set<String> dict) {        int strlen=s.length();        boolean [] table=new boolean[strlen+1];        table[0]=true;//begin is always true, so we can start the loop        for(int i=0;i<strlen;i++){            if(!table[i])// 0~i-1 are not words                continue;            for(String word: dict){                int len=word.length();                int end=i+len-1;                if(end>strlen-1)                    continue;                if(table[end+1])//already match at this position                    continue;                if(s.substring(i,end+1).equals(word)){                    table[end+1]=true;                }            }        }        return table[strlen];    }}

 

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.