Torna alle sfide
Facile 0 risolte 0% di accettazione

First Unique Character

Find the first character that appears only once.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ length ≤ 100,000

Esempi

Esempio 1
Input:
text = "swiss"

Output atteso:
expected = 1
Input:
std::string text = "swiss";

Output atteso:
long long expected = 1;
Input:
string text = "swiss";

Output atteso:
long expected = 1;

Spiegazione

s repeats, w appears once at index 1.

Esempio 2
Input:
text = "aabb"

Output atteso:
expected = -1
Input:
std::string text = "aabb";

Output atteso:
long long expected = -1;
Input:
string text = "aabb";

Output atteso:
long expected = -1;

Spiegazione

Every character repeats: -1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

Remember that uppercase and lowercase letters are different characters.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.