lintcode(107)单词切分

来源:互联网 发布:更改mac地址 编辑:程序博客网 时间:2024/06/07 07:01

Description:

给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。

Explanation:

给出

s = "lintcode"

dict = ["lint","code"]

返回 true 因为"lintcode"可以被空格切分成"lint code"

Solution:

Dynamics program.Set up boolean array dp to record whether the previous element in the dict can be substring from the string s.

Initial the dp[0] as true to start. If the current string in element can be substring from the s, then change the dp[start(it behaves the start of position in dp) + current string.length] to true.That represents the previous part of string s can be divided by the elements in dict, so we can check the next.

public class Solution {    /**     * @param s: A string s     * @param dict: A dictionary of words dict     */    public boolean wordBreak(String s, Set<String> dict) {        // write your code here         int len = s.length();        boolean[] dp = new boolean[len + 1];        dp[0] = true;                        for(int i = 0; i< len; i++){            if(!dp[i]) continue;                        for(String current : dict){                int clen = current.length();                int end = i + clen;                                if(end > len) continue;                                if(dp[end]) continue;                                if(s.substring(i , end).equals(current)){                    dp[end] = true;                }            }        }        return dp[len];    }}




原创粉丝点击