Skip to content

Instantly share code, notes, and snippets.

@jayz5
Created July 11, 2018 13:50
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 jayz5/c19cdce3eb0a64f008a2b372b5ad489d to your computer and use it in GitHub Desktop.
Save jayz5/c19cdce3eb0a64f008a2b372b5ad489d to your computer and use it in GitHub Desktop.
given a string, find its longest substring that contains two unique characters
let str = "abcbbbbcccbdddadacb"
var maxLength = 0
var startForMax = 0
// recurse
// complexity: O(N)
func search(start: Int) {
let i = start
var j = start + 1
let a = str[str.index(str.startIndex, offsetBy: i)]
var b = str[str.index(str.startIndex, offsetBy: j)]
while j < str.count && b == a {
j += 1
b = str[str.index(str.startIndex, offsetBy: j)]
}
while j < str.count && [a, b].contains(str[str.index(str.startIndex, offsetBy: j)]) {
j += 1
}
if j - i > maxLength {
maxLength = j - i
startForMax = i
}
if j < str.count - 1 {
search(start: i + 1)
}
}
// start from 0
search(start: 0)
// get the result
let substr = String(str[str.index(str.startIndex, offsetBy: startForMax)...str.index(str.startIndex, offsetBy: startForMax + maxLength - 1)])
print(substr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment