LeetCode#648 Replace Words (week14)
2017-12-06 11:54
411 查看
week14
题目
In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Note:
The input will only have lower-case letters.
1 <= dict words number <= 1000
1 <= sentence words number <= 1000
1 <= root length <= 100
1 <= sentence words length <= 1000
原题地址:https://leetcode.com/problems/replace-words/description/
解析
题目给出一个数组dict作为存放字典中的字符串,给定一个字符串sentence,要求将sentence以空格分解为子字符串,如果某个子字符串a以dict中的某个字符串b为开头,称b为a的root,用b代替sentence中对应的a,最后将sentence中的子字符串重新连接为一个字符串大致思路是先将sentence按空格分割为子字符串并存放在数组中,对于每个子字符串,查找dict中是否有字符串是其root,有则以之代替,最后用数组中的字符串及空格重新拼接成新的字符串
代码
class Solution { public: string replaceWords(vector<string>& dict, string sentence) { vector<string> words; spilt(sentence, words); replace(dict, words); string rel = ""; for (int i = 0; i < words.size(); ++i) { rel += words[i]; rel += " "; } return rel.substr(0,rel.size() - 1); } /*将字符串按空格分解*/ void spilt(string sentence, vector<string>& words) { int len = sentence.size(); int begin = 0, end = 0; int last_blank = -1; while (end < len) { /*每找到一个空格生成一个子串*/ if (sentence[end] != ' ') { ++end; } else { last_blank = end; string ss = sentence.substr(begin, end - begin); words.push_back(ss); begin = end + 1; end = begin; } } /*最后一个子串后面没有空格,单独处理*/ if (last_blank != -1) { string s = sentence.substr(last_blank + 1, len - last_blank); words.push_back(s); } } /*对于words中的每个字符串,在dict中查找root并替代*/ void replace(vector<string>& dict, vector<string>& words) { int len = words.size(); for (int i = 0; i < len; ++i) { for (int j = 0; j < dict.size(); ++j) { if (isRoot(dict[j], words[i])) { words[i] = dict[j]; break; } } } } /*比较得到字符串str是否以sub开头*/ bool isRoot(string sub, string str) { int k = 0, j = 0; while (str[k] == sub[j] && k < str.size() - 1) { if (j == sub.size() - 1) { return true; } ++k; ++j; } return false; } };
相关文章推荐
- week14---补充泛型
- week14---12月11日 JS内置对象——document文档对象、Dom对象
- LeetCode#494 Target Sum (week14)
- [week 14][Leetcode][Divide and Conquer] Majority Element
- week14_2.cpp
- LeetCode week 14: Coin Change
- week_14_ Word Search
- Data Structure - Week 14 (B)
- week 14
- Strange Printer_Week14
- Data Structure - Week 14 (A)
- leetcode 108(week 14)
- 【算法设计作业】week14
- week 14 lianxi
- 《算法分析与设计》Week 14
- LeetCode 题解(Week 14):468. Validate IP Address
- Guru of the Week 条款14:类之间的关系(上篇)
- Week 14算法分析作业
- Live NFL playoff probability updates for Week 14
- 小课堂week14 Google软件测试之道