Code Lab

Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado

Count characters in a sentence

MediaMap and Set10 min

Write a function countCharacters(sentence) that counts how many times every character occurs in a sentence.

  • sentence is a string. It can be empty.
  • Return a Map: the key is the character, the value is its count.
  • Case does not matter: 'A' and 'a' are the same character. Put letters into the Map in lower case. This is a case insensitive count.
  • Do not count whitespace: spaces, tabs ('\t') and new lines ('\n').
  • Count everything else: punctuation marks and digits too.
  • If there is nothing to count, return an empty Map.
  • Key order is not checked.

Ejemplos

countCharacters('Hi hi')

Devuelve Map(2) { 'h' => 2, 'i' => 2 }

countCharacters('Aa, 1!')

Devuelve Map(4) { 'a' => 2, ',' => 1, '1' => 1, '!' => 1 }

countCharacters('   ')

Devuelve Map(0) {}

Preguntada en Arcesium · Fuente

Cargando el editor…
  1. EntradacountCharacters('Hello World')
    EsperadoMap(7) { 'h' => 1, 'e' => 1, 'l' => 3, 'o' => 2, 'w' => 1, 'r' => 1, 'd' => 1 }
  2. EntradacountCharacters('a.b.a')
    EsperadoMap(3) { 'a' => 2, '.' => 2, 'b' => 1 }

Las pruebas ocultas se ejecutan al enviar