In this post Swift 5.0 solution given for National Coding Week Sep-2021 challenge. Given a string S of letters 'a' and/or 'b', replaces some consecutive sequence "abb" in S by "baa".
Example, S = "ababb" then "ababb" → "abbaa" → "baaaa".
Working solution :
public func solution(_ S : inout String) -> String {
var hasFound = true
var res = Array(S)
// 1
while hasFound && res.count > 2 {
hasFound = false
//2
for index in 0..<res.count-2 {
// 3
if res[index] == "a" && res[index+1] == "b" && res[index+2] == "b" {
hasFound = true
res[index] = "b"
res[index+1] = "a"
res[index+2] = "a"
break;
}
}
}
return String(res)
}
print(solution("ababb")) // prints "baaaa"
- Repeat step 2 until all the transformations completed. Also guard condition for minimum 3 characters.
- Compare every character & it's next 2 positions with 'a', 'b', 'b' respectively.
- If matched, replace the characters with 'b', 'a', 'a'.
Read complete challenge description from https://app.codility.com/programmers/challenges/national_coding_week_2021/
Thanks for reading till end. Please comment if you find useful or better solutions.