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

First Unique Character

Find the first character that appears only once.

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

  • Count characters with a dictionary
  • Make a second pass to find the first unique one
  • Solve it in linear time

โจทย์

ดูฉบับแปล

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

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

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

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

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