Last active
October 19, 2021 13:56
-
-
Save gladimdim/2c6bb2162c04060cb0afc99beaee1af6 to your computer and use it in GitHub Desktop.
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
/// You are given a string containing characters and only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string. | |
// | |
// Your task is to find the minimum number of required deletions. | |
// https://www.hackerrank.com/challenges/alternating-characters | |
int alternateCharactersLoop(String input) { | |
if (input.isEmpty) { | |
return 0; | |
} | |
var first = input[0]; | |
var counter = 0; | |
for (var i = 1; i < input.length; i++) { | |
if (first == input[i]) { | |
counter++; | |
} | |
first = input[i]; | |
} | |
return counter; | |
} | |
int alternateCharactersRecursive(String input) { | |
if (input.isEmpty) { | |
return 0; | |
} | |
var first = input[0]; | |
return _inner(input.substring(1), first, 0); | |
} | |
int _inner(String input, String char, int counter) { | |
if (input.isEmpty) { | |
return counter; | |
} | |
return _inner( | |
input.substring(1), input[0], char == input[0] ? ++counter : counter); | |
} | |
void main() { | |
print("Alternate chars"); | |
print(alternateCharactersRecursive("aaaaaaabbcaa")); | |
print(alternateCharactersRecursive("aabbccc")); | |
print(alternateCharactersLoop("aaaaaaabbcaa")); | |
print(alternateCharactersLoop("aabbccc")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment