Skip to content

Instantly share code, notes, and snippets.

@dreamolight
Created January 24, 2019 07:35
Show Gist options
  • Save dreamolight/001de1843d6cf9ee5fddfa572174b404 to your computer and use it in GitHub Desktop.
Save dreamolight/001de1843d6cf9ee5fddfa572174b404 to your computer and use it in GitHub Desktop.
class Solution {
func longestSubstring(_ s: String, _ k: Int) -> Int {
let s = s.lowercased()
var info = [Int](repeating: 0, count: 26)
let chars = Array(s.utf8CString).map { Int($0 - "a".utf8CString.first!) }.filter{ $0 >= 0 }
for c in chars {
info[c] += 1
}
var valid = Set<Int>()
for i in 0 ..< 26 {
if info[i] >= k {
valid.insert(i)
}
}
var maxLen = 0
let validNums = Array(valid).sorted()
print(validNums)
if validNums.count == 0 {
return 0
}
var len = 0
var temp = [Int](repeating: 0, count: validNums.count)
for i in 0 ..< chars.count {
if valid.contains(chars[i]) {
temp[validNums.firstIndex(of: chars[i])!] += 1
len += 1
if isValid(temp, k) {
maxLen = max(maxLen, len)
}
} else {
if isValid(temp, k) {
len = 0
temp = [Int](repeating: 0, count: validNums.count)
continue
} else {
temp = [Int](repeating: 0, count: validNums.count)
maxLen = max(maxLen, longestSubstring(String((s as NSString).substring(with: NSMakeRange(i - len, len)).reversed()), k))
len = 0
}
}
}
return maxLen
}
func isValid(_ info: [Int], _ k: Int) -> Bool {
for i in info {
if i < k && i != 0 {
return false
}
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment