Dễ 0 đã giải Tỷ lệ chấp nhận 0%

First Unique Character

Find the first character that appears only once.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

0 ≤ length ≤ 100,000

Ví dụ

Ví dụ 1
Đầu vào:
text = "swiss"

Kết quả mong đợi:
expected = 1
Đầu vào:
std::string text = "swiss";

Kết quả mong đợi:
long long expected = 1;
Đầu vào:
string text = "swiss";

Kết quả mong đợi:
long expected = 1;

Giải thích

s repeats, w appears once at index 1.

Ví dụ 2
Đầu vào:
text = "aabb"

Kết quả mong đợi:
expected = -1
Đầu vào:
std::string text = "aabb";

Kết quả mong đợi:
long long expected = -1;
Đầu vào:
string text = "aabb";

Kết quả mong đợi:
long expected = -1;

Giải thích

Every character repeats: -1.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

You need characters that appear exactly once, not just the first different one.

Gợi ý 2

Count all character frequencies first, then find the earliest position with frequency one.

Gợi ý 3

Remember that uppercase and lowercase letters are different characters.

Độ phức tạp mong đợi

O(n) time, O(k) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.