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).

解题思路:

由于涉及到对words的查询

因此第一步:将words[] put进图里,key代表单词,value代表单词次数。

考虑到s很长,一步一步走的话其实有很多时候可以利用之前的结果,因此可以以word[0].length为单位进行一次遍历(类似于奇偶),这样就可以使用前面的结果了。

然后设一个指针,每次移动word[0].length步,检查是否在words的图里面,如果有的话,也把它放到另外一张图里面,并引用一个计数器,如果计数器长度和words[].length的长度一致的话,那么找到一组解,指针后移。当然,里面有很多判断条件,具体见代码,JAVA实现:

	static public List<Integer> findSubstring(String s, String[] words) {
List<Integer> list = new ArrayList<Integer>();
if (s.length() == 0 || words.length == 0 || words[0].length() == 0)
return list;
HashMap<String, Integer> wordsMap = new HashMap<String, Integer>();
for (String string : words) {
if (!wordsMap.containsKey(string))
wordsMap.put(string, 1);
else
wordsMap.put(string, wordsMap.get(string) + 1);
}
for (int i = 0; i < words[0].length(); i++) {
int StartIndex = i, wordsLength = 0;
HashMap<String, Integer> tmap = new HashMap<String, Integer>();
for (int j = i; j <= s.length() - words[0].length(); j += words[0].length()) {
String str = s.substring(j, j + words[0].length());
if (wordsMap.containsKey(str)) {
if (tmap.containsKey(str))
tmap.put(str, tmap.get(str) + 1);
else
tmap.put(str, 1);
wordsLength++;
while (tmap.get(str) > wordsMap.get(str)) {
String startWord = s.substring(StartIndex,StartIndex + words[0].length());
StartIndex += words[0].length();
tmap.put(startWord, tmap.get(startWord) - 1);
wordsLength--;
}
if (wordsLength == words.length) {
list.add(StartIndex);
String startWord = s.substring(StartIndex,StartIndex + words[0].length());
tmap.put(startWord, tmap.get(startWord) - 1);
wordsLength--;
StartIndex += words[0].length();
}
}
else {
tmap.clear();
wordsLength = 0;
StartIndex = j + words[0].length();
}
}
}
return list;
}

最新文章

  1. Oracle数据库安装图文操作步骤
  2. Auty 2017——WebMonitor接口检测平台
  3. Caused by: java.lang.UnsatisfiedLinkError...解决经历
  4. jquery发送ajax请求返回数据格式
  5. 4月10日学习笔记——jQuery选择器
  6. 《深入Java虚拟机学习笔记》- 第2章 平台无关
  7. django celery redis简单测试
  8. RFID电子标签的二次注塑封装
  9. C++ Primer 学习笔记_61_重载操作符与转换 --自增/自减操作符
  10. 怎样用LINQ或EF生成NOT IN和IN语句
  11. 【知了堂学习心得】浅谈c3p0连接池和dbutils工具类的使用
  12. cookies相关概念
  13. 【数学建模】day08-数理统计III
  14. MVC下 Area和Web同名的Controller问题
  15. Codeforces 980D Perfect Groups 计数
  16. Tools:apache部署https服务
  17. [Spring] Aspect Oriented Programming with Spring | AOP | 切面 | 切点
  18. How to Pronounce Word vs. World
  19. 常用bios flash闪存型号
  20. 创建DataSnap Server

热门文章

  1. Yii2.0 对数据库 查询的简单操作
  2. BZOJ-1207 打鼹鼠 DP(LIS)
  3. CRUD之delete操作
  4. POJ1743 Musical Theme
  5. html中设置锚点定位的几种常见方法(#号定位)
  6. POJ2437 Muddy roads
  7. Linux /proc、/dev Principle
  8. photon mapping阶段性总结
  9. IIS负载均衡-Application Request Route详解第四篇:使用ARR实现三层部署架构(转载)
  10. linux下查看当前用户的 三个命令