本文共 818 字,大约阅读时间需要 2 分钟。
题目如下:
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"
.
动态规划的思想就是要根据前面的知识求得全局的最优解,所以该题的解法可如下:
一个boolean数组dp[n+1],其中dp[i]表示字符串s的第0个字符到第i个字符组成的字符串是否在dict中,得到关系式为dp[i] = dp[j] && wordDict.contains(s.substring(j, i))(j < i);
代码如下:
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) { boolean[] arrays = new boolean[s.length() + 1]; arrays[0] = true; int len = s.length(); for (int i = 1; i <= len; i++) { for(int j = 0; j < i; j++){ if(arrays[j] && wordDict.contains(s.substring(j, i))){ arrays[i] = true; break; }//end if }//end for j }//end for i return arrays[len]; } }
转载地址:http://qobvb.baihongyu.com/