滑动窗口-Slide Window 209,3,928,386,424,1493,395,386,76,992,3306,849,1838,2516,2537, 2781,3132, 3298
public int lengthOfLongestSubstringTwoDistinct(String s) { Map<Character,Integer> map = new HashMap(); int max = 0; int left = 0;//左侧指针 for(int i=0;i<s.length();i++){ char c = s.charAt(i); map.put(c,map.getOrDefault(c,0)+1);//1.进 当前元素进入窗口 while(map.size()>2){ //2.出 左侧元素移出窗口保证满足条件 char t = s.charAt(left++); map.put(t,map.get(t)-1); if(map.get(t)==0) map.remove(t); } max = Math.max(max,i-left+1);//3.算 计算满足条件下的最优结果 } return max; }
209. Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4] Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0
Constraints:
1 <= target <= 1091 <= nums.length <= 1051 <= nums[i] <= 105
O(n) solution, try coding another solution of which the time complexity is O(n log(n)).class Solution { public int minSubArrayLen(int target, int[] nums) { int sum = 0; int left = 0; int result = nums.length+1; for(int i=0;i<nums.length;i++){ sum+=nums[i]; while(sum>=target){ result = Math.min(result,i-left+1); sum-=nums[left++]; } } return result>nums.length ? 0 : result; } }
3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = "" Output: 0
Constraints:
0 <= s.length <= 5 * 104sconsists of English letters, digits, symbols and spaces.
class Solution { public int lengthOfLongestSubstring(String s) { Set<Character> set = new HashSet(); int max = 0; int left = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); while(set.contains(c)) set.remove(s.charAt(left++)); set.add(c); max = Math.max(max,set.size()); } return max; } }
时间复杂度:O(N)
928 · Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
Example 1
Input: “eceba”
Output: 3
Explanation:
T is "ece" which its length is 3.
Example 2
Input: “aaa”
Output: 3
public class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { Map<Character,Integer> map = new HashMap(); int max = 0; int left = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); map.put(c,map.getOrDefault(c,0)+1); while(map.size()>2){ char lc = s.charAt(left); int count = map.get(lc); if(count==1) map.remove(lc); else map.put(lc,count-1); left++; } max = Math.max(max,i-left+1); } return max; } }
时间复杂度:O(N)
386 · Longest Substring with At Most K Distinct Characters
Given a string S, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: S = "eceba" and k = 3
Output: 4
Explanation: T = "eceb"
Example 2:
Input: S = "WORLD" and k = 4
Output: 4
Explanation: T = "WORL" or "ORLD"
public class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character,Integer> map = new HashMap(); int max = 0; int left = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); map.put(c,map.getOrDefault(c,0)+1); while(map.size()>k){//只需要在上一题基础上,把2改成k即可 char lc = s.charAt(left); int count = map.get(lc); if(count==1) map.remove(lc); else map.put(lc,count-1); left++; } max = Math.max(max,i-left+1); } return max; } }
时间复杂度:O(N)
424. Longest Repeating Character Replacement
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example 1:
Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.
Constraints:
1 <= s.length <= 105sconsists of only uppercase English letters.0 <= k <= s.length
class Solution { public static int characterReplacement(String s, int k) { int[] map = new int[s.length()]; int left = 0; int max = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); map[c-'A']++; while(i-left+1-findMax(map)>k){ map[s.charAt(left)-'A']--; left++; } max = Math.max(max,i-left+1); } return max; } private static int findMax(int[] map){ int max = 0; for(int num:map) max=Math.max(max,num); return max; } }
时间复杂度: O(26N) -> O(N)
1493. Longest Subarray of 1's After Deleting One Element
Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element.
Example 4:
Input: nums = [1,1,0,0,1,1,1,0,1] Output: 4
Example 5:
Input: nums = [0,0,0] Output: 0
Constraints:
1 <= nums.length <= 105nums[i]is either0or1.
class Solution { public int longestSubarray(int[] nums) { int result=0,count=0,left=0; for(int i=0;i<nums.length;i++){ if(nums[i]==0) count++; while(count>1){ if(nums[left]==0) count--; left++; } result=Math.max(result,i-left); } return result; } }
395. Longest Substring with At Least K Repeating Characters
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
Example 1:
Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Constraints:
1 <= s.length <= 104sconsists of only lowercase English letters.1 <= k <= 105
解法:这个题如果你直接用滑动窗口做的话,当你遇到不满足条件的时候,你不知道该缩小窗口还是扩大窗口。那么我们可以穷举26种情况,那么题就可以转换为:longest substring with at least K repeating chars and distinct chars is exact N
class Solution { public int longestSubstring(String s, int k) { int max = 0; for(int uniq = 1;uniq <= 26; uniq++ ){ Map<Character,Integer> map = new HashMap(); int left = 0; int count = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); map.put(c,map.getOrDefault(c,0)+1);//先进 if(map.get(c)==k) count++; while(map.size()>uniq){//再出 char lc = s.charAt(left); int t = map.get(lc); if(t==k) count--; if(t>1) map.put(lc,t-1); else map.remove(lc); left++; } if(count==uniq) max = Math.max(max,i-left+1);//计算 } } return max; } }
时间复杂度:O(26N) -> O(N)
386 · 最多有k个不同字符的最长子字符串
给定字符串S,找到最多有k个不同字符的最长子串T。
样例 1:
输入: S = "eceba" 并且 k = 3
输出: 4
解释: T = "eceb"
样例 2:
输入: S = "WORLD" 并且 k = 4
输出: 4
解释: T = "WORL" 或 "ORLD"
O(n) 时间复杂度
public class Solution { /** * @param s: A string * @param k: An integer * @return: An integer */ public int lengthOfLongestSubstringKDistinct(String s, int k) { if(k==0) return 0; Map<Character,Integer> map = new HashMap(); int i=0,j=0; int max = 0; while(j<s.length()){ char c = s.charAt(j); int count = map.getOrDefault(c,0); if(count==0 && map.size()>=k){ max = Math.max(max,j-i); while(map.size()>=k){ char t = s.charAt(i); int temp = map.get(t); if( temp==1 ) map.remove(t); else map.put(t,temp-1); i++; } } map.put(c,count+1); j++; } max = Math.max(max,j-i); return max; } }
FollowUp: 如果你拿到的是一个非常大的文件,我们只能用Stream逐步读取, 而不是有限长度的String, 如何解决?
eabaacebdefc k=3
这个时候因为太长因此不可能把string 都保存在内存中,也就是我们无法记录滑动窗口中 i 的位置
我们可以增加一个LRU来作为辅助,使用LRU来存储元素最后一次出现的位置,当字母个数超过k时,尾部待remove的元素记录的即为i的位置
76. Minimum Window Substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.lengthn == t.length1 <= m, n <= 105sandtconsist of uppercase and lowercase English letters.
O(m + n) time?
class Solution { public String minWindow(String s, String t) { Map<Character,Integer> map = new HashMap(); //初始化目标串的各字符统计个数 for(int i=0;i<t.length();i++) map.put(t.charAt(i),map.getOrDefault(t.charAt(i),0)+1); int count = 0,result=s.length()+1,start=0; int left = 0; //遍历字符串 for(int i=0;i<s.length();i++){ char c = s.charAt(i); //如果属于目标串的字符,则对目标串统计核减,如果核减为0的,说明该字符满足条件了,count++计数 if(map.containsKey(c)) { map.put(c,map.get(c)-1); if(map.get(c)==0) count++; } //满足条件后,记录当前结果,然后开始shrink,去掉字符的过程中 while(count==map.size()){ if(result>i-left+1){ result = i-left+1; start = left; } char lc = s.charAt(left); if( map.containsKey(lc) ){ map.put(lc,map.get(lc)+1); if(map.get(lc)==1) count--; } left++; } } return result>s.length() ? "" : s.substring(start,start+result); } }
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good array is an array where the number of different integers in that array is exactly k.
- For example,
[1,2,3,1,2]has3different integers:1,2, and3.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Example 2:
Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Constraints:
1 <= nums.length <= 2 * 1041 <= nums[i], k <= nums.length
class Solution { public int subarraysWithKDistinct(int[] nums, int k) { //巧妙将恰好k个元素的情况问题,转化为:最多k个元素的情况 - 最多k-1个元素的情况 return countAtMostK(nums,k)-countAtMostK(nums,k-1); } //计算有多少种subarray,最多有k个不同的元素 private int countAtMostK(int[] nums, int k){ Map<Integer,Integer> map = new HashMap(); int result=0,left=0; for( int i=0;i<nums.length;i++ ){ map.put(nums[i],map.getOrDefault(nums[i],0)+1); while(map.size()>k){ map.put(nums[left],map.getOrDefault(nums[left],0)-1); if(map.get(nums[left])==0) map.remove(nums[left]); left++; } result+=i-left+1;//这个位置不太好理解,你可以想象:从left到i这个窗口中以i作为末尾元素的子序列个数,我们最终要把各种i结尾的子序列个数加起来 } return result; } }
时间复杂度: O(N)
You are given a string word and a non-negative integer k.
Return the total number of
word that contain every vowel ('a', 'e', 'i', 'o', and 'u') at least once and exactly k consonants.
Example 1:
Input: word = "aeioqq", k = 1
Output: 0
Explanation:
There is no substring with every vowel.
Example 2:
Input: word = "aeiou", k = 0
Output: 1
Explanation:
The only substring with every vowel and zero consonants is word[0..4], which is "aeiou".
Example 3:
Input: word = "ieaouqqieaouqq", k = 1
Output: 3
Explanation:
The substrings with every vowel and one consonant are:
word[0..5], which is"ieaouq".word[6..11], which is"qieaou".word[7..12], which is"ieaouq".
Constraints:
5 <= word.length <= 2 * 105wordconsists only of lowercase English letters.0 <= k <= word.length - 5
class Solution { /** 难点:无法使用滑动窗口计算类似aeioubaeiou k=1 的的count 思路:将exactly k consonants 转化为: (at least k consonants) - (at least k-1 consonants) 然后就可以使用滑动窗口, 1.以一个left为起始,找到一个右侧点i满足5个不同元音以及k个辅音,那么i右侧每个点都可以作为终点满足条件,因此满足条件的有:len-i 2.可以移动左侧指针left,继续进行滑动窗口计算 */ public long countOfSubstrings(String word, int k) { return countAtLeast(word, k) - countAtLeast(word, k + 1); } private Set<Character> vows = Set.of('a', 'e', 'i', 'o', 'u'); private long countAtLeast(String word, int k) { Map<Character, Integer> map = new HashMap<>(); int consCount = 0; int left = 0; long result = 0; for(int i = 0; i < word.length(); i++) { char c = word.charAt(i); if(vows.contains(c)) { map.put(c, map.getOrDefault(c, 0) + 1); } else { consCount++; } while(map.size() == 5 && consCount >= k) { result += word.length() - i; char remove = word.charAt(left++); if(vows.contains(remove)) { map.put(remove, map.get(remove) - 1); if(map.get(remove) == 0) map.remove(remove); } else { consCount--; } } } return result; } }
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1 Output: 0 Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Output: 16
Constraints:
1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.length
解法:这题跟上面一道是类似的解法
class Solution { public int numberOfSubarrays(int[] nums, int k) { return countAtMostK(nums,k)-countAtMostK(nums,k-1); } private int countAtMostK(int[] nums, int k){ int oddCount=0; int result=0,left=0; for(int i=0;i<nums.length;i++){ if(nums[i]%2==1) oddCount++; while(oddCount>k){ if(nums[left]%2==1) oddCount--; left++; } result+=i-left+1; } return result; } }
时间复杂度: O(N)
849. Maximize Distance to Closest Person
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.
Example 1:
Input: seats = [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2.
Example 2:
Input: seats = [1,0,0,0] Output: 3 Explanation: If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3.
Example 3:
Input: seats = [0,1] Output: 1
Constraints:
2 <= seats.length <= 2 * 104seats[i]is0or1.- At least one seat is empty.
- At least one seat is occupied.
解法一:不推荐该解法,1.没有使用模版,代码写起来容易出错 2.使用了3个循环,实际该题可以1pass
class Solution { public int maxDistToClosest(int[] seats) { int l=0,r=0; int max = 0; while(r<seats.length){ while(l<seats.length && seats[l]==1) { l++;r=l; } if(r>=seats.length) break; if(r<seats.length && seats[r]==1){ max = Math.max((r-l+1)/2,max); l=r+1; r=l; } r++; } for(int i=0;i<seats.length;i++){ if(seats[i]!=0) { max = Math.max(max,i); break; } } for(int i=seats.length-1;i>=0;i--){ if(seats[i]!=0) { max = Math.max(max,seats.length-i-1); break; } } return max; } }
推荐解法:
class Solution { public int maxDistToClosest(int[] seats) { int left=-1; int max = 0; for(int i=0;i<seats.length;i++){ if(seats[i]==1){ max = Math.max(max,left<0 ? i : (i-left)/2);//left<0时为作左边界corner case left = i; } } max = Math.max(max,seats.length-1-left); //别忘了右边界corner case return max; } }
更清晰做法是:
1. 滑动窗口求去最大空档 gap/2
2.过程中记录了左侧和右侧空档
3. 三者取最大
1838. Frequency of the Most Frequent Element
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
Example 1:
Input: nums = [1,2,4], k = 5 Output: 3 Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. 4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5 Output: 2 Explanation: There are multiple optimal solutions: - Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. - Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. - Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2 Output: 1
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1051 <= k <= 105
class Solution { public int maxFrequency(int[] nums, int k) { //先排序,保证升序 Arrays.sort(nums); //使用sliding window int left = 0, max = 1; for(int i=1;i<nums.length;i++){ //右指针右移的时候,前面窗口中的每个元素都需要消耗 nums[i]-nums[i-1] int minus = (nums[i]-nums[i-1])*(i-left); k -= minus; //如果k成为负数,说明k不够用,左指针需要右移,直到k>=0 while(k<0){ //左指针右移的时候,将最左侧元素占用的吐出来 int plus = nums[i]-nums[left]; k += plus; left++; } //记录当前的最大window max = Math.max(max, i-left+1); } return max; } }
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2 Output: 3 Explanation: The substring is "ece" with length 3.
Example 2:
Input: s = "aa", k = 1 Output: 2 Explanation: The substring is "aa" with length 2.
Constraints:
1 <= s.length <= 5 * 1040 <= k <= 50
class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> map = new HashMap(); int left = 0; int result = 0; for(int i = 0;i < s.length(); i++){ char c = s.charAt(i); map.put(c, map.getOrDefault(c, 0)+1); while(map.size() > k){ char rc = s.charAt(left++); int count = map.get(rc); if(count == 1) map.remove(rc); else map.put(rc, count-1); } result = Math.max(result, i-left+1); } return result; } }
2516. Take K of Each Character From Left and Right
You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.
Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.
Example 1:
Input: s = "aabaaaacaabc", k = 2 Output: 8 Explanation: Take three characters from the left of s. You now have two 'a' characters, and one 'b' character. Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters. A total of 3 + 5 = 8 minutes is needed. It can be proven that 8 is the minimum number of minutes needed.
Example 2:
Input: s = "a", k = 1 Output: -1 Explanation: It is not possible to take one 'b' or 'c' so return -1.
Constraints:
1 <= s.length <= 105sconsists of only the letters'a','b', and'c'.0 <= k <= s.length
解法:
题目要求从头尾remove最少的character来满足至少k个a,b,c ,我们可以转化为首位相连的字符串中,寻找满足k个abc的最小子串
关键问题是:子串的范围要覆盖到头或者尾
实现:
1.我们可以将str+str进行拼接为新的string
2.利用sliding window寻找满足条件的最小子串,但是前提条件是子串范围覆盖到了头/尾
class Solution { public int takeCharacters(String s, int k) { if(k == 0) return 0; int len = s.length(); //字符串进行拼接 s = s + s; int left = 0, result = len + 1; int[] count = new int[3]; //one pass扫描字符串 for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); count[c - 'a']++; // 1.k条件满足 2.左右边界覆盖到了原串的头或尾 while(isValid(count, k) && left <= len && i >= len - 1){ result = Math.min(result, i - left + 1); count[s.charAt(left++) - 'a']--; } } return result == len + 1 ? -1 : result; } private boolean isValid(int[] count, int k){ if(count[0] >= k && count[1] >= k && count[2] >= k) return true; return false; } }
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,1,1,1,1], k = 10 Output: 1 Explanation: The only good subarray is the array nums itself.
Example 2:
Input: nums = [3,1,4,3,2,2,4], k = 2 Output: 4 Explanation: There are 4 different good subarrays: - [3,1,4,3,2,2] that has 2 pairs. - [3,1,4,3,2,2,4] that has 3 pairs. - [1,4,3,2,2,4] that has 2 pairs. - [4,3,2,2,4] that has 2 pairs.
Constraints:
1 <= nums.length <= 1051 <= nums[i], k <= 109
class Solution { public long countGood(int[] nums, int k) { Map<Integer, Integer> map = new HashMap(); int count = 0, left = 0; long result = 0; for(int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); //每次重复次数k,count就会增加k-1次 count += map.get(nums[i]) - 1; while(count >= k) { map.put(nums[left], map.get(nums[left]) - 1); //count减少k次 count -= map.get(nums[left]); left++; //右边有多少个多余的字符,就会有多少种组合 result += nums.length - i; } } return result; } }
2781. Length of the Longest Valid Substring
You are given a string word and an array of strings forbidden.
A string is called valid if none of its substrings are present in forbidden.
Return the length of the longest valid substring of the string word.
A substring is a contiguous sequence of characters in a string, possibly empty.
Example 1:
Input: word = "cbaaaabc", forbidden = ["aaa","cb"] Output: 4 Explanation: There are 9 valid substrings in word: "c", "b", "a", "ba", "aa", "bc", "baa", "aab", and "aabc". The length of the longest valid substring is 4. It can be shown that all other substrings contain either "aaa" or "cb" as a substring.
Example 2:
Input: word = "leetcode", forbidden = ["de","le","e"] Output: 4 Explanation: There are 11 valid substrings in word: "l", "t", "c", "o", "d", "tc", "co", "od", "tco", "cod", and "tcod". The length of the longest valid substring is 4. It can be shown that all other substrings contain either "de", "le", or "e" as a substring.
Constraints:
1 <= word.length <= 105wordconsists only of lowercase English letters.1 <= forbidden.length <= 1051 <= forbidden[i].length <= 10forbidden[i]consists only of lowercase English letters.
class Solution: def longestValidSubstring(self, word: str, forbidden: List[str]) -> int: #将forbidden放入set,便于快速检索是否存在 fset = set(forbidden) #检查当前串是否满足条件 def valid(curr): temp, clen = "", len(curr) ''' 1.题目明确提到forbidden元素len最长只有10 2.这里是将curr从右向左逐个拼接检查,为啥不是从左向右?因为左侧已经在右指针移动中做了检查 ''' for i in range(0, 10): if i >= clen: return True temp = curr[clen - i - 1] + temp if temp in fset: return False return True #滑动窗口,得到最大长度 left, result, curr = 0, 0, collections.deque() for i in range(0, len(word)): curr.append(word[i]) while not valid(curr): curr.popleft() left += 1 result = max(result, i - left + 1) return result
You are given two integer arrays nums1 and nums2.
From nums1 two elements have been removed, and all other elements have been increased (or decreased in the case of negative) by an integer, represented by the variable x.
As a result, nums1 becomes equal to nums2. Two arrays are considered equal when they contain the same integers with the same frequencies.
Return the minimum possible integer x that achieves this equivalence.
Example 1:
Input: nums1 = [4,20,16,12,8], nums2 = [14,18,10]
Output: -2
Explanation:
After removing elements at indices [0,4] and adding -2, nums1 becomes [18,14,10].
Example 2:
Input: nums1 = [3,5,5,3], nums2 = [7,7]
Output: 2
Explanation:
After removing elements at indices [0,3] and adding 2, nums1 becomes [7,7].
Constraints:
3 <= nums1.length <= 200nums2.length == nums1.length - 20 <= nums1[i], nums2[i] <= 1000- The test cases are generated in a way that there is an integer
xsuch thatnums1can become equal tonums2by removing two elements and addingxto each element ofnums1.
class Solution { public int minimumAddedInteger(int[] nums1, int[] nums2) { /** 思路: 1. 先sort,然后逐个元素进行匹配 2. 最多删除两个元素,因此num2的第一个元素最多和num1的第1,2,3个元素进行匹配 */ int result = Integer.MAX_VALUE; Arrays.sort(nums1); Arrays.sort(nums2); // nums2的第一个元素,只能与nums1的0,1,2 这3个元素配对 for(int shift = 0; shift <= 2; shift++) { int diff = nums2[0] - nums1[shift]; int ind1 = shift;//nums1从shift 开始 boolean valid = true; for(int ind2 = 0; ind2 < nums2.length; ind2++) { // 如果当前配对与diff不匹配,并且ind1还可以drop元素,那么ind1++ while(ind1 <= ind2 + 2 && diff != nums2[ind2] - nums1[ind1]) { ind1++; } // 如果发现ind1已经超出偏移范围,或者仍然不相等,退出当前比对 if(ind1 > ind2 + 2 || diff != nums2[ind2] - nums1[ind1]) { valid = false; break; } ind1++; } // 如果比对成功,记录最佳答案 if(valid) result = Math.min(result, diff); } return result; } }
word1 and word2.A string x is called valid if x can be rearranged to have word2 as aprefixReturn the total number of valid substrings of word1.Note that the memory limits in this problem are smaller than usual, so you must implement a solution with a linear runtime complexity.
Example 1:
Input: word1 = "bcca", word2 = "abc"
Output: 1
Explanation:
The only valid substring is "bcca" which can be rearranged to "abcc" having "abc" as a prefix.
Example 2:
Input: word1 = "abcabc", word2 = "abc"
Output: 10
Explanation:
All the substrings except substrings of size 1 and size 2 are valid.
Example 3:
Input: word1 = "abcabc", word2 = "aaabc"
Output: 0
Constraints:
1 <= word1.length <= 1061 <= word2.length <= 104word1andword2consist only of lowercase English letters.
class Solution { /** 思路,滑动窗口 */ public long validSubstringCount(String word1, String word2) { HashMap<Character, Integer> map = new HashMap<>(); int count = 0; for(char c : word2.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } int left = 0; long result = 0; for(int i = 0; i < word1.length(); i++) { char c = word1.charAt(i); // 如果目标串中存在,那么进行扣减 if(map.containsKey(c)) { map.put(c, map.get(c) - 1); if(map.get(c) == 0) count++; } // 如果当前满足条件,移动left指针直至不满足 while(count == map.size()) { //记录当前满足的个数 result += word1.length() - i; char lc = word1.charAt(left++); if(map.containsKey(lc)) { map.put(lc, map.get(lc) + 1); if(map.get(lc) == 1) count--; } } } return result; } }
395,992

浙公网安备 33010602011771号