word-break

題目描述

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

IDEA

字符串被字典分割。動態規劃法,用dp[i]=true表示s[0,..,i]的子字符串是能被分割

s.strsub(j,i-j)表示取s中從j到i(不包括i)的子串

CODE

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        int len=s.length();
        vector<bool> dp(len+1,false);
        dp[0]=true;
        for(int i=1;i<=len;i++){
            for(int j=i-1;j>=0;j--){
                if(dict.find(s.substr(j,i-j))!=dict.end()&&dp[j]){
                    dp[i]=true;
                }
            }
        }
        return dp[len];
    }
};


發佈了230 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章