您的位置:首页 > 其它

139.Word Break

2015-04-08 00:02 134 查看


Word Break

 Total Accepted: 44934 Total
Submissions: 198482My Submissions

Question
 Solution 

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"
.

Show Tags
 Dynamic Programming

Have you met this question in a real interview? 
Yes
 
No

Discuss
思路:动态规划:1.dp[i]表示s[0....i]能否由dict组成;2.递推关系是 如果dp[i]可以,则遍历dict中的单词,如果该单词在以s[i+1]开始的位置,则dp[i+单词长度]也可以
class Solution {

public:

    bool wordBreak(string s, unordered_set<string> &dict) {

        int n=s.size();

        if(n==0) return false;//判错

        //初始化

        bool *dp=new bool
;

        for(int i=0;i<n;++i){

            dp[i]=false;

        }

        for(auto i:dict){

            if(s.find(i)==0){

                dp[i.size()-1]=true;

            }

        }

        //dp过程

        int pos=0;

        while(pos<n){

            if(dp[pos]){

                ++pos;

                for(auto i:dict){

                    if(s.find(i,pos)==pos){

                        dp[pos+i.size()-1]=true;

                    }

                }

            }else{

                ++pos;

            }

        }

        //输出

        bool res=dp[n-1];

        delete []dp;

        return res;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: