Substring with Concatenation of All Words--LeetCode
来源:互联网 发布:女网球运动服知乎 编辑:程序博客网 时间:2024/06/05 18:09
1.题目
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).
2.题意
不额外插入字符,找出串联列表中所有单词的子串的起始位置
每个单词的长度相同
3.分析
借助两个哈希表
m1记录所有单词出现的次数
每次找出给定单词长度的子串,看其是否在m1里
如果不存在,立即break
如果有,则加入m2,如果该单词在m2中出现次数更多,也break
如果正好匹配完words里所有的单词,则i存入result
一定要注意两个点
i<=(int)s.size()-m*n中的==号不要遗漏,s.size()要类型转换
int j=0;放在循环外,否则得到的结果为空
4.代码
class Solution {public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> result; int len = s.size(); int m = words.size(); if(len == 0 || m == 0) return result; unordered_map<string, int> m1; for(auto &tmp : words) ++m1[tmp]; int n = words[0].size(); for(int i = 0; i <= len - m * n; ++i) { unordered_map<string, int> m2; int j = 0; for(j = 0; j < m; ++j) { string tmp = s.substr(i + j * n, n); if(m1.find(tmp) == m1.end()) break; ++m2[tmp]; if(m2[tmp] > m1[tmp]) break; } if(j == m) result.push_back(i); } return result; }};
阅读全文
0 0
- LeetCode: Substring with Concatenation of All Words
- LeetCode : Substring with Concatenation of All Words
- [Leetcode] Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- LeetCode:Substring with Concatenation of All Words
- Leetcode: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words
- LeetCode | Substring with Concatenation of All Words
- LeetCode - Substring with Concatenation of All Words
- Substring with Concatenation of All Words -- LeetCode
- Leetcode: Substring with Concatenation of All Words
- leetcode:Substring with Concatenation of All Words
- LeetCode|Substring with Concatenation of All Words
- DataTimeDemo,MathDemo,程序异常
- [ Java学习 ] 静态内部类
- perl书籍
- java 多线程
- angular自定义指令详解
- Substring with Concatenation of All Words--LeetCode
- (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作
- 数组
- POJ 1742/HDU2844 Coins 题解
- MachineLearning 学习之fisher判别
- 最长公共上升子序列
- Django 博客
- Unix-Linux编程实践教程——第六章
- 空间亚线性算法