Bhavya

Code -> Break -> Fix -> Blog


Leave a comment

Mettl Coding Test : Find the max. distance between two occurrences of a char in a string

Problem Statement:

  1. Write a method to find the max. distance between two occurrences of a char in a string.
  2. Distance is the no. of unique characters (excluding whitespaces and searched character) between two occurrences of the searched character.

Example 1:

SearchLetter(“my name is granar”, “a”);

Output : 7 (i.e. m,e,i,s,g,r,n)

Example 2:

SearchLetter(“the capital of minnesota is saint paul”, “y”);

Output : -1 (no. occurrence of “y”)

Example 3:

SearchLetter(“quick brown fox jumps over the lazy dog”, “a”);

Output : -1 (only 1 occurrence of “a”)

Solution

public static int output1;

public static void SearchLetter(string input1, string input2)
{
if (string.IsNullOrEmpty(input1)
|| string.IsNullOrEmpty(input2)
|| input1.Count() < 2
|| input2.Count() != 1)
{
output1 = -1;
return;
}

var firstIndex = input1.IndexOf(input2);
var lastIndex = input1.LastIndexOf(input2);

if (firstIndex == lastIndex)
{
output1 = -1;
return;
}

var distance = lastIndex - firstIndex;
var finalSearchString = input1.Substring(firstIndex + 1, distance - 1);

finalSearchString = finalSearchString.Replace(" ", string.Empty)
.Replace(input2, string.Empty);

string tempString = string.Empty;
string finalString = string.Empty;

foreach (var value in finalSearchString)
{
if (tempString.IndexOf(value) == -1)
{
tempString += value;
finalString += value;
}
}

output1 = finalString.Count();
}

~BJS
 

Advertisements


1 Comment

String replace C# (without using built IN methods)

1. Simple replace:

public static string MyReplaceSimple(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);

 var result = new StringBuilder();

 for (int i = 0; i < sourceArr.Length; i++)
 {
 result.Append(sourceArr[i]);

 if (i + 1 != sourceArr.Length)
 {
 result.Append(newValue);
 }
 }

 return result.ToString();
 }
 return null;
 }

2. Replace using LINQ:

public static string MyReplaceLinq(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);
 var start = sourceArr.Take(1);
 var end =
 from originalString in sourceArr.Skip(1)
 from newString in new[] { newValue, originalString }
 select newString;
 var result = String.Join("", start.Concat(end));
 return result;
 }

 return null;
 }

Happy coding…

~BS