Code Lab

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

Fewest changes, no equal neighbours

DifícilStrings15 min

Write a function minChanges(s) that returns the smallest number of changes you need so that no two characters next to each other in the string s are equal.

  • One change replaces one character with any other character.
  • s has 0 to 10000 characters. Characters are compared exactly: 'a' and 'A' are different. Any character can appear: letters, digits, spaces, punctuation like '*' or '!'.
  • Return a whole number. For an empty string and a string with no equal neighbours return 0.
  • The rule: split the string into runs of equal characters next to each other. A run of length L needs Math.floor(L / 2) changes: in 'aaaa' you change the second and the fourth a ('abab'), so 2 changes. Add up the numbers for all runs.

One loop over the string is enough: count the length of the current run and add its changes when the run ends.

Ejemplos

minChanges('aab')

Devuelve 1

minChanges('aaaa')

Devuelve 2

minChanges('aabbcc')

Devuelve 3

Preguntada en Cred · Fuente

Cargando el editor…
  1. EntradaminChanges('aab')
    Esperado1
  2. EntradaminChanges('aaaa')
    Esperado2
  3. EntradaminChanges('abc')
    Esperado0

Las pruebas ocultas se ejecutan al enviar