@Okma this is wrong. Your code only keeps track of the last task, and only waits for cooldown if the last task is the same as the new one.
For example with the input: ABA with K=5, the correct answer is 7, because after completing B we still have to wait 4 more time units before we can start A again. But your code returns 3 because the if condition is never true.
A correct solution would be to keep for each task the last time this task started, so when this task has to start again we can wait for (full or partial) cooldown. If tasks are known to be called A-Z just keep this in an array. If the string is unicode, keep a map/dictionary.