leetcode 判断字符串是否可以划分为字典序的单词(动态规划)

#include<unordered_set>
#include<string>
#include<iostream>
bool Judge(string s, unordered_set<string> &dict)
{
	int len = s.length();
	vector<bool>res(len + 1, false);//res[i]表示从0~i-1在字典中是否存在
	res[0] = true;
	for (int pos = 0; pos < len; pos++){//从pos位置开始进行字符串截取并判断
		for (int i = pos; res[pos] && i < len; i++){//res[pos]也要进行判断,i-pos+1表示后面截取多少个字符(由1开始递增)
			if (dict.find(s.substr(pos, i - pos + 1)) != dict.end())//
				res[i + 1] = true;
		}
	}
	return res[len];
}
int main()  
{
	string s = "leetcode";
	unordered_set<string> dict = { "leet", "cod" };
	bool f = Judge(s, dict);
	getchar();
	return 0;
}

https://www.nowcoder.com/questionTerminal/5f3b7bf611764c8ba7868f3ed40d6b2c

猜你喜欢

转载自blog.csdn.net/liugg2016/article/details/82119498