leetcode 102: Substring with Concatenation of All Words
来源:互联网 发布:如何更改淘宝用户名 编辑:程序博客网 时间:2024/04/29 13:11
Substring with Concatenation of All WordsFeb 24 '12
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
[思路]
brute force, 按顺序一个一个查过去. 因为L是无序且有可能重复, 所以建一个map记录L中word的个数. 没遇到一个word删除, 当map为空时, 即找到一个substring满足要求.
public class Solution { public ArrayList<Integer> findSubstring(String S, String[] L) { // Start typing your Java solution below // DO NOT write main() function ArrayList<Integer> res = new ArrayList<Integer>(); if(S==null || L==null || L.length==0) return res; HashMap<String, Integer> map = new HashMap<String, Integer>(); for(int i=0; i<L.length; i++){ if(map.containsKey( L[i] ) ){ map.put(L[i], map.get(L[i])+1); } else { map.put(L[i], 1); } } int sz= S.length(); int m=L[0].length(); int n=L.length; for(int i=0; i<sz-n*m+1;i++) { HashMap<String, Integer> temp = new HashMap<String, Integer>(map); for(int j=i; j<i+n*m;j+=m) { String t = S.substring(j,j+m); if( temp.containsKey(t) ){ int x=temp.get(t); if(x==1) temp.remove(t); else temp.put(t, x-1); } else { break; } if(temp.isEmpty()) { res.add(i); } } } return res; }}
- 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
- 直接插入排序
- NULL指针
- ppp拨号脚本配置
- 为何HTML和CSS的注释标签会有所不相同?
- IntelliJ IDEA 12 与 Tomcat集成并运行Web项目 配置
- leetcode 102: Substring with Concatenation of All Words
- 折半插入排序
- [Android实例] 毕业设计共享(Android+SSH2+REST)----移动警务查询系统
- 用SQL命令查看Mysql数据库大小
- JS学习之一(null、 undefined、 0、 false、 "")
- 单链表基础操作C++实现
- 大数相乘
- Android 请求rest
- activeMQ 和 tomcat