leetcode做题记录0030

leetcode 0030

说明

只是为了记录一下,不求多快,也不深究。

会简要描述思路,代码中不写注释。

如碰到不会做的用了别人代码会在博客中标出。

题目描述

在这里插入图片描述

参考

参考了B站up主noicfanker的讲解,以下是视频链接:

【LeetCode 30. 串联所有单词的子串】 每天一题刷起来!C++ 年薪冲冲冲!

思路

这题里有一个点就是每个单词长度是一样的,这是个关键。

用一个map记录words中的单词,key为单词本身,value为出现次数。

在s中截取相同的长度,因为单词的长度是一样的,所以很好切分。

再用一个map2存当前截取字符串中的单词和词频。

比较两个map,相同则往list中加入相应的索引,不同则滑动窗口继续向下滑。

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
		List<Integer> res = new ArrayList<Integer>();
		if (words.length == 0) {
			return res;
		}
		int wordLen = words[0].length();
		int len = words.length * wordLen;
		if (len > s.length()) {
			return res;
		}
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (String word : words) {
			if (map.containsKey(word)) {
				map.put(word, map.get(word) + 1);
			} else {
				map.put(word, 1);
			}
		}
		flag: for (int i = 0; i + len <= s.length(); ++i) {
			String temp = s.substring(i, i + len);
			Map<String, Integer> map2 = new HashMap<String, Integer>();
			for (int j = 0; j < len; j += wordLen) {
				String temp2 = temp.substring(j, j + wordLen);
				if (map2.containsKey(temp2)) {
					map2.put(temp2, map2.get(temp2) + 1);
				} else {
					map2.put(temp2, 1);
				}
			}
			if (map.size() != map2.size()) {
				continue;
			} else {
				for (String key : map.keySet()) {
					if (!map2.containsKey(key)) {
						continue flag;
					}
					if (map.get(key) != map2.get(key)) {
						continue flag;
					}
				}
				res.add(i);
			}
		}
		return res;
	}
}
发布了77 篇原创文章 · 获赞 1 · 访问量 2064

猜你喜欢

转载自blog.csdn.net/Paul_1i/article/details/104967952