Retour aux défis
Facile 0 résolus 0 % de réussite

First Unique Character

Find the first character that appears only once.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

0 ≤ length ≤ 100,000

Exemples

Exemple 1
Entrée :
text = "swiss"

Sortie attendue :
expected = 1
Entrée :
std::string text = "swiss";

Sortie attendue :
long long expected = 1;
Entrée :
string text = "swiss";

Sortie attendue :
long expected = 1;

Explication

s repeats, w appears once at index 1.

Exemple 2
Entrée :
text = "aabb"

Sortie attendue :
expected = -1
Entrée :
std::string text = "aabb";

Sortie attendue :
long long expected = -1;
Entrée :
string text = "aabb";

Sortie attendue :
long expected = -1;

Explication

Every character repeats: -1.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

Remember that uppercase and lowercase letters are different characters.

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.