

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to find the 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]
- Related Questions & Answers
- C++ Program to find the Shortest Distance to a character
- How to find the longest distance to a character in a given string using C#?
- Find Shortest distance from a guard in a Bankin Python
- How to find a unique character in a string using java?
- Java program to find the Frequency of a character in a given String
- Corresponding shortest distance in string in JavaScript
- How to find the vowels in a given string using Java?
- Program to Find the Shortest Distance Between Two Points in C++
- Find the index of the first unique character in a given string using C++
- How to find consonants in a given string using Java?
- How to find its first non-repeating character in a given string in android?
- How to find the first character of a string in C#?
- Python program to change character of a string using given index
- Shortest Distance to Target Color in C++
- Find the first repeated character in a string using C++.
Advertisements