โจทย์
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
ตัวอย่าง
อินพุต:
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".
อินพุต:
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน