leetcode:Substring with Concatenation of All Words
2015-08-20 16:32
447 查看
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 words exactly 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).
题意
给定一个字符串S和一个字符串数组L,L中的字符串长度都相等,找出S中所有的子串,该子串恰好包含L中所有字符各一次并且不含其他字符,返回所有这样子串的起始位置。
分析
把字符串数组L建一个Map字符窗,将字符窗从字符串S的第一个字符开始匹配并向后滑动,直到S的最后一个字符,输出匹配结果。
C++11代码
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 words exactly 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).
题意
给定一个字符串S和一个字符串数组L,L中的字符串长度都相等,找出S中所有的子串,该子串恰好包含L中所有字符各一次并且不含其他字符,返回所有这样子串的起始位置。
分析
把字符串数组L建一个Map字符窗,将字符窗从字符串S的第一个字符开始匹配并向后滑动,直到S的最后一个字符,输出匹配结果。
C++11代码
// 时间复杂度O(n*m),空间复杂度O(m) class Solution { public: vector<int> findSubstring(string s, vector<string>& dict) { size_t wordLength = dict.front().length(); size_t catLength = wordLength * dict.size(); vector<int> result; if (s.length() < catLength) return result; unordered_map<string, int> wordCount; for (auto const& word : dict){ ++wordCount[word]; } for (auto i = begin(s); i <= prev(end(s), catLength); ++i) { unordered_map<string, int> unused(wordCount); for (auto j = i; j != next(i, catLength); j += wordLength) { auto pos = unused.find(string(j, next(j, wordLength))); if (pos == unused.end() || pos->second == 0) break; if (--pos->second == 0) unused.erase(pos); } if (unused.size() == 0) result.push_back(distance(begin(s), i)); } return result; } };
相关文章推荐
- Objective-c之NSArray(NSMutableArray)
- (15)Visual Studio中使用PCL项目加入WCF WebService参考
- MySQL数据库常用命令集
- WPF 多项选择下拉菜单
- 序列化二进制方法的实现
- 在类Unix系统上开始Python3编程入门
- 虚拟化--003 利用vsphere client来开启esxi的ssh功能
- 9. 斐波那契数列
- 虚拟化--002 VMware vSphere 创建虚拟机时SCSI适配器的选择
- 神经网络编程入门
- 暑假-动态规划 III-I - Function Run Fun
- DOM(一)-18-(节点操作-删除节点)
- linux调试工具
- JVM查看命令
- 二叉树的链式存储
- (14)[Xamarin.Android] 异步的网络图片下载
- ios delegate 使用注意 assign,weak
- HA之heartbeat3.0.6安装配置
- static作用整理
- 分数加减法