Created
July 11, 2018 13:50
-
-
Save jayz5/c19cdce3eb0a64f008a2b372b5ad489d to your computer and use it in GitHub Desktop.
given a string, find its longest substring that contains two unique characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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