Problem · Dynamic Programming
String Challenge (Generic)
Learn this problemProblem statement
At the TikTok Academy, students are learning how to improve video captions.
You are given a string caption that only has small Englsh letters ('a' to 'z'). You can make two kinds of changes to caption at any letter as many times as needed.
For example, you can change 'f' to 'e' (the letter before) or 'g' (the letter after).
What is your task this time? They want you to make that every letter in the caption has at least one same letter next to it. For example, "aaabb" and "aaccdd" are goooood, but "abaaa" and "abcdef" are veryyy bad 😭
Plz return the min num of changes needed to make the caption meets the rules mentioned above.
Thanks to Da Best Spike!⸜(。˃ ᵕ ˂ )⸝♡
Function
stringChallenge(caption: String) → intExamples
Example 1
caption = "aca"return = 2You can change 'c' to 'b' (the letter before 'c'), then 'b' to 'a' (the letter before 'b'). Now the caption is 'aaa', which meets the rule. (This line of text might be slightly diff from the original explanation, but it should do well at capturing the meaning of the original explanation :)
You will need 2 changes to meet the rule, which is min possible.
So the ans is 2 :)
Example 2
caption = "abcdef"return = 3You can change caption[0] from 'a' to 'b' (the letter after :)
cpation[3] from 'd' to 'c' (the letter before)
and caption[4] from 'e' to 'f' (the letter after)
now the caption is "bbccff", which meets the rule.
In total, you'd need 3 chagnes to meet the rule, which is minimum possible.
So, the answer is 3. (I think 2 is the typo on the image source)
Example 3
caption = "abab"return = 2You can change caption[0] from 'a' to 'b' (the letter after)
change caption[3] from 'b' to 'a' (the letter before :)
Now the caption is "bbaa", which meets the rule.
In total, you need 2 changes to meet the rule, which is the min possible.
So, return 2 as answer :P
Constraints
2 <= |caption| <= 105