[LeetCode]139.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”.

思路

递归

代码

/*—————————————* 日期:2015-05-07* 作者:SJF0115* 题目: 139.Word Break* 网址:https://leetcode.com/problems/word-break/* 结果:AC* 来源:LeetCode* 博客:—————————————–*/;class Solution {public:bool wordBreak(string s, unordered_set<string>& wordDict) {int size = wordDict.size();if(size == 0){return false;}//ifvector<bool> visited(s.size(),false);return helper(s,wordDict,0,visited);}private:bool helper(string &s,unordered_set<string>& wordDict,int index,vector<bool> &visited){if(index >= s.size()){return true;}(visited[index]){return false;}//ifvisited[index] = true;// 以index下标开始for(int i = index;i < s.size();++i){if(wordDict.find(s.substr(index,i – index + 1)) != wordDict.end()){if(helper(s,wordDict,i+1,visited)){return true;}//if}//if};}};int main() {Solution solution;string str(“leetcode”);unordered_set<string> wordDict = {“leet”,”co”,”code”};cout<<solution.wordBreak(str,wordDict)<<endl;}

运行时间

,不论你在什么时候结束,重要的是结束之后就不要悔恨

[LeetCode]139.Word Break

相关文章:

你感兴趣的文章:

标签云: