[Swift]LeetCode1100. 長度爲 K 的無重複字符子串 | Find K-Length Substrings With No Repeated Characters

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fmvwztsz-kz.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example 1:github

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:this

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

給你一個字符串 S,找出全部長度爲 K 且不含重複字符的子串,請你返回所有知足要求的子串的 數目。 spa

示例 1:code

輸入:S = "havefunonleetcode", K = 5
輸出:6
解釋:
這裏有 6 個知足題意的子串,分別是:'havef','avefu','vefun','efuno','etcod','tcode'。

示例 2:htm

輸入:S = "home", K = 5
輸出:0
解釋:
注意:K 可能會大於 S 的長度。在這種狀況下,就沒法找到任何長度爲 K 的子串。 

提示:blog

  1. 1 <= S.length <= 10^4
  2. S 中的全部字符均爲小寫英文字母
  3. 1 <= K <= 10^4

44msci

 1 class Solution {
 2     func numKLenSubstrNoRepeats(_ S: String, _ K: Int) -> Int {
 3         var ans:Int = 0
 4         let n:Int = S.count
 5         let S:[Int] = Array(S).map{$0.ascii}
 6         for i in 0..<n
 7         {
 8             var freq:[Int] = [Int](repeating:0,count:26)
 9             var j:Int = i
10             var len:Int = 0
11             while(j < n)
12             {
13                 //a:97
14                 if freq[S[j] - 97] != 0 {break}
15                 freq[S[j] - 97] += 1
16                 len += 1
17                 j += 1
18                 if len == K
19                 {
20                     ans += 1
21                 }
22             }
23         }
24         return ans
25     }
26 }
27 
28 //Character擴展
29 extension Character
30 {
31     //Character轉ASCII整數值(定義小寫爲整數值)
32     var ascii: Int {
33         get {
34             return Int(self.unicodeScalars.first?.value ?? 0)
35         }
36     }
37 }
相關文章
相關標籤/搜索