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

Every Other Character

Keep the characters at even positions.

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

  • เลือกอักขระที่ตำแหน่งคู่
  • วนลูปทีละ 2 หรือใช้การตัดสตริง
  • สร้างสตริงใหม่

โจทย์

Build a new string from the characters of text at positions 0, 2, 4, … (every other character, starting with the first).

Implement every_other_character(text).

Input

text: The original text.

Output

Return the characters at even positions, in order.

เงื่อนไข

0 ≤ length of text ≤ 10,000

ตัวอย่าง

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

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

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

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

คำอธิบาย

Positions 0, 2, 4, 6, 8, 10 give p, o, r, m, i, g: "pormig".

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

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

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

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

คำอธิบาย

Only position 0 exists: "a".

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

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

คำใบ้ 1

ต้องการตัวอักษรที่อยู่ตำแหน่ง 0, 2, 4 และต่อ ๆ ไป

คำใบ้ 2

การไล่แบบกระโดดทีละสองตำแหน่งคือวิธีที่ง่ายที่สุด

คำใบ้ 3

ถ้าข้อความว่างหรือมีความยาวคี่ รูปแบบนี้ก็ยังใช้ได้ตามปกติ

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

เวลา O(n), หน่วยความจำเพิ่ม O(n)

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

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

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

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

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