Intern
# Étant donné une chaîne composée des lettres 'X', 'Y' et 'O'. # Il faut trouver la distance la plus courte entre les lettres 'X' et 'Y', # ou retourner 0 si 'X' ou 'Y' sont absentes. # "YY" -> 0 # "XX" -> 0 # "XY" -> 1 # "YOX" -> 2 # "OOOXOOYOXO" -> 2 # "OOOXXOY" -> 2 def distance(string: str) -> int:
sobes.tech IA
Réponse de l'IA
def distance(chaine: str) -> int: # Vérifions la présence de 'X' et 'Y' dans la chaîne if 'X' not in chaine or 'Y' not in chaine: return 0
positions_x = [i for i, ch in enumerate(chaine) if ch == 'X']
positions_y = [i for i, ch in enumerate(chaine) if ch == 'Y']
min_dist = float('inf')
i, j = 0, 0
# Utilisons deux pointeurs pour rechercher la distance minimale
while i < len(positions_x) and j < len(positions_y):
dist = abs(positions_x[i] - positions_y[j])
if dist < min_dist:
min_dist = dist
# Déplaçons le pointeur pour trouver une distance plus petite
if positions_x[i] < positions_y[j]:
i += 1
else:
j += 1
return min_dist