โจทย์
Return the index of the first character in text that appears exactly once. Case matters.
Implement first_unique_index(text).
Input
text: The text to inspect.
Output
Return the index, or -1 if every character repeats.
เงื่อนไข
0 ≤ length ≤ 100,000
ตัวอย่าง
อินพุต:
text = "swiss"
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
std::string text = "swiss";
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
string text = "swiss";
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
s repeats, w appears once at index 1.
อินพุต:
text = "aabb"
ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::string text = "aabb";
ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
string text = "aabb";
ผลลัพธ์ที่คาดหวัง:
long expected = -1;
คำอธิบาย
Every character repeats: -1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
You need characters that appear exactly once, not just the first different one.
คำใบ้ 2
Count all character frequencies first, then find the earliest position with frequency one.
คำใบ้ 3
Remember that uppercase and lowercase letters are different characters.
ความซับซ้อนที่คาดหวัง
O(n) time, O(k) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน