1 滑动窗口 方法解法
c++
letcode 3数组
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。3d
示例 1:code
输入: "abcabcbb"
输出: 3
解释: 由于无重复字符的最长子串是 "abc",因此其长度为 3。blog
遇到没有重复的字符就日后+1,那新+1的数据怎么知道与前面的元素是否重复呢?(不能一次次扫 这个子串)这里能够设置一个数组 freq[256]的 freq[k]对应一个字符的ASCII值的频率。若是是0就是没有重复字符串
代码:string
class Solution { public: int lengthOfLongestSubstring(string s) { int freq[256] = {0}; //256个位置,初始化为0 int l = 0, r = -1; int res = 0; while(l<s.size()){ if(freq[s[r+1]]==0 && r+1 < s.size()) freq[s[++r]]++; else freq[s[l++]]--; res = max(res,r-l+1); } return res; } };
letcode 209io
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中知足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。若是不存在符合条件的子数组,返回 0。class
示例:方法
输入:s = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
解题思路 采用 滑动窗口的方法
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int l =0,r = -1; int sum = 0; int index = nums.size()+1; while(l<nums.size()){ if (r+1<nums.size()&& sum<s){ sum+=nums[++r]; }else{ sum-=nums[l++]; } if(sum>=s){ index = min(index,r-l+1); } } if(index == nums.size()+1){ return 0; } return index; } };