
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Shortest Distance to a Character in a Given String using C#
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 minimum of both the arrays.
Time Complexity − O(n)
Space Complexity − O(n)
Example
public class Arrays{ public int[] ShortestDistanceToCharacter(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.Min(leftDis[i], rightDis[i]); } return ans; } } static void Main(string[] args){ Arrays s = new Arrays(); string ss = "lovecode"; char c = 'e'; var res = s.ShortestDistanceToCharacter(ss, c); foreach (var item in res){ Console.WriteLine(item); } }
Output
[3,2,1,0,1,2,1,0]
Advertisements