Skip to content

Instantly share code, notes, and snippets.

@xr1337
Created August 10, 2020 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xr1337/9f87d6087368876fc6cf16739bf8c5e8 to your computer and use it in GitHub Desktop.
Save xr1337/9f87d6087368876fc6cf16739bf8c5e8 to your computer and use it in GitHub Desktop.
unique substrings
import Cocoa
func fewestCoins(coins: String) -> Int {
let coinsArray = Array(coins)
let checkSet :Set = Set(coinsArray)
let countedSet :NSCountedSet = NSCountedSet()
// validation when the lenght of the string == amount uniq characters
if(checkSet.count == coins.count || checkSet.count == 0) {
return coins.count
}
// brute force with sliding window
var left = 0, right = 0, smallResult = coins.count
while (right < coinsArray.count || left < coinsArray.count ) {
if (countedSet.count == checkSet.count) {
smallResult = min(smallResult, right - left)
left += 1
countedSet.remove(coinsArray[left])
} else if right < coinsArray.count {
countedSet.add(coinsArray[right])
right += 1
} else {
countedSet.remove(coinsArray[left])
left += 1
}
}
return Int(smallResult)
}
fewestCoins(coins: "asdfkjeghfalawefhaef")
fewestCoins(coins: "bab")
fewestCoins(coins: "cbbbdcbba")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment