标签:leetcode dictionary 动态规划 segment
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],表示第i个字符以前是否可以分隔成单词。 i 从0开始。
已知dp[0..i]时,求dp[i+1],则需要偿试,s[k..i], 0<=k <=i, 进行偿试。
在leetcode上实际执行时间为12ms。
class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> dp(s.size()+1);
        dp[0] = true;
        for (int i=1; i<=s.size(); i++) {
            for (int j=0; j<i; j++) {
                if (dp[j] && wordDict.find(s.substr(j, i-j)) != wordDict.end()) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};标签:leetcode dictionary 动态规划 segment
原文地址:http://blog.csdn.net/elton_xiao/article/details/46315201