ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Reverse a String

Return the characters of a string in reverse order.

สิ่งที่คุณจะได้เรียนรู้

  • Walk through a string backwards
  • Build a new string from characters
  • Use slicing or two pointers

โจทย์

ดูฉบับแปล

Reverse text so the last character comes first.

Implement reverse_string(text).

Input

text: The text to reverse.

Output

Return the reversed text.

เงื่อนไข

0 ≤ length ≤ 10,000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
text = "hello"

ผลลัพธ์ที่คาดหวัง:
expected = "olleh"
อินพุต:
std::string text = "hello";

ผลลัพธ์ที่คาดหวัง:
std::string expected = "olleh";
อินพุต:
string text = "hello";

ผลลัพธ์ที่คาดหวัง:
string expected = "olleh";

คำอธิบาย

h-e-l-l-o read backwards is "olleh".

ตัวอย่างที่ 2
อินพุต:
text = "a"

ผลลัพธ์ที่คาดหวัง:
expected = "a"
อินพุต:
std::string text = "a";

ผลลัพธ์ที่คาดหวัง:
std::string expected = "a";
อินพุต:
string text = "a";

ผลลัพธ์ที่คาดหวัง:
string expected = "a";

คำอธิบาย

A single character reversed is itself.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

The answer is the characters in opposite order.

คำใบ้ 2

A two-pointer approach or a backward traversal both work well.

คำใบ้ 3

Be sure the empty string stays empty after reversal.

ความซับซ้อนที่คาดหวัง

O(n) time, O(n) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก