Leetcode-word-break

来源:互联网 发布:英雄钢笔美工9018 编辑:程序博客网 时间:2024/06/07 01:52

题目描述


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]表示0-i长度的单词是否可分

import java.util.*;public class Solution {    public boolean wordBreak(String s, Set<String> dict) {        int n = s.length();        boolean[] dp = new boolean[n+1];dp[0] = true;for(int i=1; i<=n; i++){for(int j=0; j<i; j++){if(dp[j] && dict.contains(s.substring(j,i))){dp[i] = true;break;}}}return dp[n];    }}


0 0
原创粉丝点击