-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
46 lines (42 loc) · 1.32 KB
/
Solution.cs
File metadata and controls
46 lines (42 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Text;
namespace LeetCode.Problem2000{
//2000. Reverse Prefix of Word
//https://leetcode.com/problems/reverse-prefix-of-word/
/*
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at
the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive).
The resulting string will be "dcbaefd".
Return the resulting string.
*/
public class Solution {
public string ReversePrefix(string word, char ch) {
int index = word.IndexOf(ch);
return word.Contains(ch) ? new string (word.Substring(0,index + 1).Reverse().ToArray())+word.Substring(index + 1) : word;
}
}
public class Alternative{
public string ReversePrefix(string word, char ch) {
if (!word.Contains(ch))
return word;
StringBuilder sb = new StringBuilder();
int left = 0;
int right = 0;
while (right < word.Length - 1 && word[right] != ch)
right++;
left = right;
while (left >= 0)
{
sb.Append(word[left]);
left--;
}
right++;
while (right < word.Length)
{
sb.Append(word[right]);
right++;
}
return sb.ToString();
}
}
}