LeetCode 30. Substring with Concatenation of All Words
来源:互联网 发布:淘宝自己开的店铺呢 编辑:程序博客网 时间:2024/06/03 22:58
这题做了好几次都超时。答案是看的别人的博客学习的。。
public class Solution { public List<Integer> findSubstring(String s, String[] words) { List<Integer> res = new LinkedList<Integer>(); if(words == null || words.length == 0 || s == null || s.equals("")) return res; HashMap<String, Integer> freq = new HashMap<String, Integer>(); // 统计数组中每个词出现的次数,放入哈希表中待用 for(String word : words){ freq.put(word, freq.containsKey(word) ? freq.get(word) + 1 : 1); } // 得到每个词的长度 int len = words[0].length(); // 错开位来统计 for(int i = 0; i < len; i++){ // 建一个新的哈希表,记录本轮搜索中窗口内单词出现次数 HashMap<String, Integer> currFreq = new HashMap<String, Integer>(); // start是窗口的开始,count表明窗口内有多少词 int start = i, count = 0; for(int j = i; j <= s.length() - len; j += len){ String sub = s.substring(j, j + len); // 看下一个词是否是给定数组中的 if(freq.containsKey(sub)){ // 窗口中单词出现次数加1 currFreq.put(sub, currFreq.containsKey(sub) ? currFreq.get(sub) + 1 : 1); count++; // 如果该单词出现次数已经超过给定数组中的次数了,说明多来了一个该单词,所以要把窗口中该单词上次出现的位置及之前所有单词给去掉 while(currFreq.get(sub) > freq.get(sub)){ String leftMost = s.substring(start, start + len); currFreq.put(leftMost, currFreq.get(leftMost) - 1); start = start + len; count--; } // 如果窗口内单词数和总单词数一样,则找到结果 if(count == words.length){ String leftMost = s.substring(start, start + len); currFreq.put(leftMost, currFreq.get(leftMost) - 1); res.add(start); start = start + len; count--; } // 如果截出来的单词都不在数组中,前功尽弃,重新开始 } else { currFreq.clear(); start = j + len; count = 0; } } } return res; }}
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
- Oracle同义词创建及其作用
- Android-TabLayout使用小结
- Windows常用软件离线下载地址
- 设计模式(一)之单例模式
- C++ getline
- LeetCode 30. Substring with Concatenation of All Words
- java如何快速得到一个数组里面有多少种元素?
- 大话数据结构学习笔记2
- Mac OS X+ Selenium + ChromeDriver +Java使用例子
- VPN之——CentOS6.5建OpenVPN服务器,客户端要访问服务器同网段其他IP的设置
- UVa10012箱子得有多大
- 166.n1-事件分发,让父类不要拦截
- PYTHON解释
- 科研的一些感想