Leetcode---面试题 17.13. 恢复空格---每日一题---动态规划+字典树

面试题 17.13. 恢复空格

哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"I reset the computer. It still didn’t boot!“已经变成了"iresetthecomputeritstilldidntboot”。在处理标点符号和大小写之前,你得先把它断成词语。当然了,你有一本厚厚的词典dictionary,不过,有些词没在词典里。假设文章用sentence表示,设计一个算法,把文章断开,要求未识别的字符最少,返回未识别的字符数。

注意:本题相对原题稍作改动,只需返回未识别的字符数

示例:

输入:
dictionary = [“looked”,“just”,“like”,“her”,“brother”]
sentence = “jesslookedjustliketimherbrother”
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。

提示:

  • 0 <= len(sentence) <= 1000
  • dictionary中总字符数不超过 150000。
  • 你可以认为dictionary和sentence中只包含小写字母。

实现代码

class Trie {
public:
	Trie* next[26] = {nullptr};
	bool isEnd;
	
	Trie() {
		// 初始化字典树的截止标记
		isEnd = false;
	}

	void insert(string s) {
		Trie* now = this;
		for (int i = s.length() - 1; i >= 0; i--) {
			int index = s[i] - 'a';
			if (now->next[index] == nullptr) {
				now->next[index] = new Trie();
			}
			now = now->next[index];
		}
		// 终止标记
		now->isEnd = true;
	}
};

class Solution {
public:
	const int inf = 0x3f3f3f3f;

	int respace(vector<string>& dictionary, string sentence) {
		int len = sentence.length();
		if (!len) return 0;
		vector<int> dp(len + 1, inf); 
		Trie* root = new Trie();
		for (string s : dictionary) {
			root->insert(s);
		}
		dp[0] = 0;
		for (int i = 1; i <= len; i++) {
			// 一般情况
			dp[i] = dp[i - 1] + 1;
			// 特殊情况
			Trie* now = root;
			for (int j = i - 1; j >= 0; j--) {
				if (dp[i] == 0) break;
				int index = sentence[j] - 'a';
				if (now->next[index] == nullptr) {
					// 该字符没有匹配,直接退出
					break;
				}
				else if (now->next[index]->isEnd) {
					if (dp[j] < dp[i]) dp[i] = dp[j];
				}
				now = now->next[index];
			}
		}
		return dp[len];
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值