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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值