โจทย์
A sign-up form receives ages as text. An entry is valid when, after trimming spaces at both ends, it consists only of digits (no sign) and its value is between 0 and 150 inclusive.
Find the first invalid entry so the form can point the user to it.
Implement first_invalid_age(values).
Input
values: The typed ages, in form order.
Output
Return the index of the first invalid entry, or -1 if all of them are valid.
เงื่อนไข
0 ≤ number of entries ≤ 10,000
Each entry has at most 20 characters
ตัวอย่าง
อินพุต:
values = ["25", " 40 ", "abc", "200"]
ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
std::vector<std::string> values = {"25", " 40 ", "abc", "200"};
ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
string[] values = new string[] {"25", " 40 ", "abc", "200"};
ผลลัพธ์ที่คาดหวัง:
long expected = 2;
คำอธิบาย
"25" and " 40 " (spaces trimmed) are valid; "abc" at index 2 is the first invalid entry.
อินพุต:
values = ["0", "150", "007"]
ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::vector<std::string> values = {"0", "150", "007"};
ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
string[] values = new string[] {"0", "150", "007"};
ผลลัพธ์ที่คาดหวัง:
long expected = -1;
คำอธิบาย
All three are digits between 0 and 150 (007 is 7), so the answer is -1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Trim the entry, then check it is non-empty and made only of digits.
คำใบ้ 2
Only after that, compare its value with 150.
คำใบ้ 3
A minus sign makes the entry invalid, and 007 is a valid 7.
ความซับซ้อนที่คาดหวัง
O(total length) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน