LeetCode每日一题:分词1

问题描述

Given a string s and a dictionary of words dict, determine if s can 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".

问题分析

典型的动态规划,设dp[i]表示s的0到i位是否可分,那么状态转移方程就可以写为:
dp[i]=dp[j]是否可分+s[j,i]是否可分,其中j的取值范围在[0,i]之间
所以我们只需判断s[j,i]是否被包含在dict中即可

代码实现

public boolean wordBreak(String s, Set dict) {
        int len = s.length();
        boolean[] dp = new boolean[len + 1];//dp[i]表示s中0到i可分
        dp[0] = true;
        for (int i = 1; i <= len; i++)
            for (int j = 0; j < i; j++) {
                if (dp[j] && dict.contains(s.substring(j, i))) {
                    dp[i] = true;
                }
            }
        return dp[len];
    }

你可能感兴趣的:(LeetCode每日一题:分词1)