LeetCode 1100. Find K-Length Substrings With No Repeated Characters


原题链接在这里:https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/

题目:

Given a string S, return the number of substrings of length K with no repeated characters.

Example 1:

Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. 

Example 2:

Input: S = "home", K = 5 Output: 0 Explanation: Notice K can be larger than the length of S. In this case is not possible to find any substring.

Note:

  1. 1 <= S.length <= 10^4
  2. All characters of S are lowercase English letters.
  3. 1 <= K <= 10^4

题解:

Ask for the number of Size K window having no repeated characters.

Have runner to point the char in S. When frequency of this char is already >0, which means it appears before, then have count of repeated characters plus 1.

If runner >= K, then decrement S.charAt(runner-K) frequency. If its frequency is > 1 before decrement, then count of repeated characters minus 1.

If runner >= K-1 and there is no repeated characters, then res++.

Time Complexity: O(n). n = S.length.

Space: O(1).

AC Java: 

 1 class Solution {
 2     public int numKLenSubstrNoRepeats(String S, int K) {
 3         if(S == null || S.length() < K){
 4             return 0;
 5         }
 6         
 7         int [] map = new int[26];
 8         int runner = 0;
 9         int count = 0;
10         int res = 0;
11         while(runner < S.length()){
12             if(map[S.charAt(runner)-'a']++ > 0){
13                 count++;
14             }
15             
16             if(runner >= K){
17                 if(map[S.charAt(runner-K)-'a']-- > 1){
18                     count--;
19                 }
20             }
21             
22             if(runner >=K-1 && count == 0){
23                 res++;
24             }
25             
26             runner++;
27         }
28         
29         return res;
30     }
31 }

类似Longest Substring Without Repeating Characters.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM