[LeetCode]Substring with Concatenation of All Words
来源:互联网 发布:条形码集中打印软件 编辑:程序博客网 时间:2024/06/05 18:30
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).
思路:
利用两个数据结构toFind ,hasFound分别表示需要找的字符串和已经查找到的字符串
然后遍历s,如果能够按 words[0].length为步长查找 words.length 步满足 toFind 和 hasFound 一致的话
则表示查找到一个满足的组合
代码:
public List<Integer> findSubstring(String s, String[] words) { List<Integer> rs = new LinkedList<Integer>(); Map<String, Integer> toFind = new HashMap<String, Integer>(); Map<String, Integer> hasFound = new HashMap<String, Integer>(); for (int i = 0; i< words.length; ++i){//去重 if(toFind.get(words[i]) == null){ toFind.put(words[i], 1); }else { toFind.put(words[i], toFind.get(words[i]) + 1); } } int wordsCount = words.length; int step = words[0].length(); int loop = s.length() - wordsCount * step;//循环查找的次数 for(int i = 0; i <= loop; ++ i){//外层循环保遍历所有可能的顺序字符串 hasFound.clear(); int j =0; for(; j < wordsCount; ++j){ int k = i + j * step;//以step为单元 String sub = s.substring(k, k + step); if(! toFind.containsKey(sub)) break; if(hasFound.containsKey(sub)){ hasFound.put(sub, hasFound.get(sub) + 1); }else { hasFound.put(sub, 1); } if(hasFound.get(sub) > toFind.get(sub)) break; } if(j == wordsCount) rs.add(i); } return rs; }
1 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
- Android:客户端和服务器之间传输数据加密
- iscroll的一些基本的使用,网上找的有很多
- AJAX简单介绍
- C#连接数据库
- 微信开发开发技巧汇总(学习柳峰老师微信开发笔记)
- [LeetCode]Substring with Concatenation of All Words
- centos 安装openfire
- leetcode之 median of two sorted arrays
- nyoj-1167-阅读理解(筛法+打表)
- 实现mfc进程和qt进程之间的通信
- 写一个浮框固定在页面,单击可以消失
- Dijkstra算法求解单源点到其余各顶点的最短距离
- codeforces #398C Tree and Array 构造
- QT中QTableWidget的一些常用用法