当前位置:   article > 正文

LC-拆分词句_给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得

给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得

分词


//拆分词句word break
/*
给定一个字符串s和一组单词dict,
判断s是否可以用空格分割成一个单词序列,
使得单词序列中所有的单词都是dict中的单词(序列可以包含一个或多个单词)。
*/

#include<string>
#include<unordered_set>
#include<vector>
using namespace std;

class Solution {
public:
	//dp数组 标志s[0-i]是否可划分为dict中的子串
	bool match(string str, unordered_set<string> &dict)
	{
		if (dict.find(str) != dict.end())
			return true;
		return false;
	}

	bool wordBreak(string s, unordered_set<string> &dict) {
		if ( s.length()==0 || dict.size() == 0)
			return false;
		int strlen = s.length();
		vector<bool> dp(strlen + 1, false);
		dp[0] = true;
		for (int i = 0; i < strlen; ++i)
		{
			for (int j = i; dp[i] && j < strlen; ++j)

			{
				if (match(s.substr(i, j - i + 1), dict))
				{
					dp[j+1] = true;
				}
			}
		}
		return dp[strlen];
	}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/718478
推荐阅读
相关标签
  

闽ICP备14008679号