Intuition
Find position of ch (if any) then use two pointers to swap characters until string is reveresed from beginning to index of ch
Approach
Start by checking each character for ch. If we find it, that's where our right pointer will start. Our left pointer will start at the beginning of the string.
While left is less than right swap characters and then decrement right, and increment left. When they meet the substring beginning at index 0 and ending at the index of ch will be reversed.
Code
public class Solution
{
public string ReversePrefix(string word, char ch)
{
var arr = word.ToCharArray();
int left = 0;
int right = 0;
//find pos of ch if it exists
while(right < arr.Length && arr[right] != ch)
{
right++;
}
if(right == arr.Length)
{
//if not return the original word
return word;
}
//two pointers, one at ch, the other at the start of the string
while(left < right)
{
//swap the two characters, increase the left pointer, decrease the right
var temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
//when both pointers meet, return
return new string(arr);
}
}
About the author
I am a developer from Nashville, TN. I specialize in the .NET tech stack. I have created many projects in Blazor WASM, Xamarin, MAUI, etc.
Comments
Join the discussionNo comments yet. Be the first to comment.
LeetCode journey
A series documenting my journey to improving my ability to solve LeetCode problems through YouTube videos, study plans, articles, etc. Using my own words for later reference.