[leetcode] 30. Substring with Concatenation of All Words 解题报告
2015-12-18 04:40
656 查看
题目链接:https://leetcode.com/problems/substring-with-concatenation-of-all-words/
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation
of each word in wordsexactly once and without any intervening characters.
For example, given:
s:
words:
You should return the indices:
(order does not matter).
思路:一种比较粗暴的方式就是先对words计数,然后在s的每个位置开始枚举固定的长度,如果能找到每个单词那就把当前的索引加到结果集合中.其实这样效率还是可以接受的.时间复杂度是O(n*k),其中n是s的长度,k是总共words的长度.
代码如下:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation
of each word in wordsexactly once and without any intervening characters.
For example, given:
s:
"barfoothefoobarman"
words:
["foo", "bar"]
You should return the indices:
[0,9].
(order does not matter).
思路:一种比较粗暴的方式就是先对words计数,然后在s的每个位置开始枚举固定的长度,如果能找到每个单词那就把当前的索引加到结果集合中.其实这样效率还是可以接受的.时间复杂度是O(n*k),其中n是s的长度,k是总共words的长度.
代码如下:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { if(s.size()==0 || words.size()==0) return {}; vector<int> result; unordered_map<string, int> hash; for(auto val: words) hash[val]++; int m = words.size(), n = words[0].size(), len = s.size(); if(len < m*n) return {}; for(int i = 0, j; i <= len - m*n; i++) { unordered_map<string, int> find; for(j = i; j < i + m*n; j+= n) { string tem = s.substr(j, n); find[tem]++; if(!hash.count(tem) || find[tem] > hash[tem]) break; } if(j >= i+m*n) result.push_back(i); } return result; } };
相关文章推荐
- 【jQuery】调用stop()方法停止当前所有动画效果
- 【jQuery】调用animate()方法制作移动位置的动画
- 【jQuery】调用animate()方法制作简单的动画效果
- Vba Json
- 【jQuery】使用fadeTo()方法设置淡入淡出效果的不透明度
- 利用VBA将excel数据表生成JSON文件(utf8)
- Excel2Unity
- [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)
- 【jQuery】使用fadeIn()与fadeOut()方法实现淡入淡出效果
- [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium
- 51Nod 1163 最高的奖励(贪心+优先队列 & 并差集)
- [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图
- [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍
- [Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论
- 【jQuery】使用slideToggle()方法实现图片“变脸”效果
- [Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒
- [Python] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题
- 【jQuery】使用slideUp()和slideDown()方法的滑动效果
- 拓扑序列变形 之 poj 1094 Sorting It All Out
- [python爬虫] Selenium定向爬取海量精美图片及搜索引擎杂谈