-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
95 lines (74 loc) · 2.04 KB
/
Solution.cs
File metadata and controls
95 lines (74 loc) · 2.04 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System.Text;
namespace LeetCode.Problem557{
//557. Reverse Words in a String III
//https://leetcode.com/problems/reverse-words-in-a-string-iii/
/*
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace
and initial word order.
*/
public class Solution {
public string ReverseWords(string s) {
string[] words = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.Length; i++)
{
sb.Append(new string (words[i].Reverse().ToArray()));
sb.Append(" ");
}
sb.Remove(sb.Length -1,1);
return sb.ToString();
}
}
public class Alternative {
public string ReverseWords(string s) {
StringBuilder sb = new StringBuilder();
int left = 0;
int right = 0;
while (right < s.Length)
{
if (s[right] == ' ')
{
int tmp = right;
while (tmp > left)
{
tmp--;
sb.Append(s[tmp]);
}
sb.Append(' ');
left = right + 1;
}
if (right == s.Length -1)
{
int tmp = right;
while (tmp >= left)
{
sb.Append(s[tmp]);
tmp--;
}
}
right++;
}
return sb.ToString();
}
}
public class WithStack {
public string ReverseWords(string s) {
StringBuilder sb = new StringBuilder();
Stack<char> st = new Stack<char>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] != ' ')
st.Push(s[i]);
else
{
while (st.Count > 0)
sb.Append(st.Pop());
sb.Append(' ');
}
}
while (st.Count > 0)
sb.Append(st.Pop());
return sb.ToString();
}
}
}