สร้างเมธอด reverseWords ที่รับอาร์เรย์ char เป็นอินพุต และสำหรับแต่ละตัวอักษรจนกว่าจะเจอช่องว่าง ให้กลับคำนั้น ในขั้นตอนสุดท้ายให้กลับสตริงทั้งหมดจากความยาว 0 ถึง n-1 ในขั้นตอนแรก สตริง "This is my book" จะกลายเป็น "koob ym si siht" ในขั้นตอนที่สอง คำจะถูกกลับลำดับเป็น "book my is This"
Time complexity - O(N)
ตัวอย่าง
using System;
namespace ConsoleApplication
{
public class Arrays
{
static void reverse(char[] str, int start, int end)
{
char temp;
while (start <= end)
{
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
public char[] reverseWords(char[] s)
{
int start = 0;
for (int end = 0; end < s.Length; end++)
{
if (s[end] == ' ')
{
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, 0, s.Length - 1);
return s;
}
}
class Program
{
static void Main(string[] args)
{
Arrays a = new Arrays();
string s = " This is my book ";
var res = a.reverseWords(s.ToCharArray());
Console.WriteLine(new String(res));
Console.ReadLine();
}
}
}
ผลลัพธ์
book my is This