每日一练 52--54 滑动窗口

 连续字符字串,遇到连续子串先想滑动窗口

52

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/MPnaiL/

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的某个变位词。

换句话说,第一个字符串的排列之一是第二个字符串的 子串 。

func checkInclusion(s1 string, s2 string) bool {
	var start,end int
	plength:=len(s1)
	slength:=len(s2)
	need := [26]int{}
	window := [26]int{}
	end = plength
	for i:=start;i<end&&i<slength;i++{
		window[s2[i]-'a']++
		need[s1[i]-'a']++
	}
	for start<=slength-plength{
		if window==need{
			return true
		}
		window[s2[start]-'a']--
		if end ==slength{
			break
		}
		window[s2[end]-'a']++
		start++
		end++
	}
	return false
}

53

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/VabMRr/

给定两个字符串 s 和 p,找到 s 中所有 p 的 变位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

变位词 指字母相同,但排列不同的字符串。

func findAnagrams(s string, p string) []int {
	var start,end int
	var res []int
	plength:=len(p)
	slength:=len(s)
	need := [26]int{}
	window := [26]int{}
	end = plength
	for i:=start;i<end&&i<slength;i++{
		window[s[i]-'a']++
		need[p[i]-'a']++
	}
	for start<=slength-plength{
		if window==need{
			res =append(res,start)
		}
		window[s[start]-'a']--
		if end ==slength{
			break
		}
		window[s[end]-'a']++
		start++
		end++
	}
	return res
}

54

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/wtcaE1/

给定一个字符串 s ,请你找出其中不含有重复字符的 最长连续子字符串 的长度。

//最长子串,第一反应就应该是滑动窗口
func lengthOfLongestSubstring(s string) int {
	var start,end,res int
	hashmap:=make(map[uint8]int)
	for end<len(s){
		hashmap[s[end]]++
		if hashmap[s[end]]==1{
			//第一次出现
			tmp:=end - start + 1
			if tmp >res{
				res = tmp
			}
		}else{
			for start<=end && hashmap[s[end]]>1{
				hashmap[s[start]]--
				start++
			}
		}
		end++
	}
	return res
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值