I would like to know any suggestions about to improve my code and/or get a better approach for this problem solution and your rating of my approach to the problem.(besides removing the if
statements where the amount+= 0;
I'm aware that it should be there)
Description
Write a function that, given a string S consisting of N character. Returns the maximum number of letters 'a' that can be inserted into S. so that the resulting string doesn't contain three consecutive letters 'a'. If the string S contains substring 'aaa', then the function should return -1.
Examples:
- S = "aabab" should return 3 "aabaabaa"
- S = "dog" should return 8 "aadaaoaagaa"
- S = "aa" should return 0
- S = "baaaa" should return -1 S = "a" should return 1 "aa"
Comments explanation:
- capital letters represent the original str content
- "A" means the char the "forbidden character"
- "B" means any other character
- "a" means "inserted" a
The Code
private static int FindMaxInsert(string str)
{
int amount =0;
const char forbiddenChar = 'a';
if (str.Contains("aaa"))
{
amount = -1;
}
else
{
if (str.Length == 1)
{
if (str[0] == forbiddenChar)
amount = 1; //A - > aA || Aa
else
amount = 4; // B - > aaBaa
}
else if (str.Length == 2)
{
if ((str[0] == forbiddenChar && str[1] != forbiddenChar) || (str[0] != forbiddenChar && str[1] == forbiddenChar))
amount = 3; // A B || B A -> aABaa || aaBAa
}
else if (str.Length > 2)//prevnet against empty string
{
if (str[0] != forbiddenChar)
amount += 2;
if (str[str.Length - 1] != forbiddenChar)
amount += 2;
for (int i = 0; i < str.Length - 2; i += 2) //search insert between
{
char first = str[i];
char middle = str[i + 1];
char last = str[i + 2];
if (first == forbiddenChar && middle == forbiddenChar && last == forbiddenChar)
amount += 0; // A A A - > cant
else if (first == forbiddenChar && middle == forbiddenChar && last != forbiddenChar)
amount += 0; // A A B -> cant
else if (first == forbiddenChar && middle != forbiddenChar && last == forbiddenChar)
amount += 2; // A B A -> AaBaA
else if (first == forbiddenChar && middle != forbiddenChar && last == forbiddenChar)
amount += 0; // B A A -> cant
else if (first == forbiddenChar && middle != forbiddenChar && last != forbiddenChar)
amount += 3; // A B B -> AaBaaB
else if (first != forbiddenChar && middle == forbiddenChar && last != forbiddenChar)
amount += 1; // B A B - > BaAB || BAaB
else if (first != forbiddenChar && middle != forbiddenChar && last == forbiddenChar)
amount += 3; // B B A -> BaaBaA || BaaBAa
else if (first != forbiddenChar && middle != forbiddenChar && last != forbiddenChar)
amount += 4; // B B B -> BaaBaa
}
}
}
return amount;
}
public static void Main(string[] args)
{
Console.WriteLine("dog " + FindMaxInsert("dog"));
Console.WriteLine("aabab " + FindMaxInsert("aabab"));
Console.WriteLine("aa " + FindMaxInsert("aa"));
Console.WriteLine("a " + FindMaxInsert("a"));
Console.WriteLine("Empty " + FindMaxInsert(String.Empty));
}