How to find the longest distance to a character in a given string using C#?

CsharpServer Side ProgrammingProgramming

Create 2 different arrays leftDis and rightDis. The leftDis will store the value when moved from left direction. The rightDis will store the shortest value when moved from right. Whenever the character is met add the position of the character to the array. In the last step calculate the maximum of both the arrays.

Time Complexity − O(n)

Space Complexity − O(n)

Example

public class Arrays{
   public int[] LongestDistanceToCharacter(string s, char c){
      int stringLength = s.Length;
      int[] leftDis = new int[s.Length];
      int[] rightDis = new int[s.Length];
      leftDis = Enumerable.Range(0, s.Length).Select(n => int.MinValue).ToArray();
      rightDis = Enumerable.Range(0, s.Length).Select(n => int.MaxValue).ToArray();
      int count = int.MaxValue;
      for (int i = 0; i < rightDis.Length; i++){
         if (s[i] == c){
            count = 0;
            rightDis[i] = count;
         }
         else{
            if (count != int.MaxValue){
               count++;
               rightDis[i] = count;
            }
         }
      }
      count = int.MaxValue;
      for (int i = leftDis.Length - 1; i >= 0; i--){
         if (s[i] == c){
            count = 0;
            leftDis[i] = count;
         }
         else{
            if (count != int.MaxValue){
               count++;
               leftDis[i] = count;
            }
         }
      }
      int[] ans = new int[stringLength];
      for (int i = 0; i < stringLength - 1; i++){
         ans[i] = Math.Max(leftDis[i], rightDis[i]);
      }
      return ans;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   string ss = "lovecode";
   char c = 'e';
   var res = s.LongestDistanceToCharacter(ss, c);
   foreach (var item in res){
      Console.WriteLine(item);
   }
}

Output

[2147483647,2147483647,2147483647,0,3,2,3,0]
raja
Published on 17-Aug-2021 07:13:26
Advertisements