Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Algoritmos de cadenas
Algoritmos de cadenas
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Debates

Guía de Algoritmos de cadenas · 1/6

Concepts

Por ahora, este capítulo solo está disponible en inglés.

String algorithms are techniques for working with sequences of characters quickly and correctly. Find-in-file, log search, search-box autocomplete and DNA sequence comparison all ask the same question: where does this run of characters occur? This chapter fixes the vocabulary used throughout the guide and starts from the simplest approach, naive matching, to show why better algorithms exist.

Vocabulary

TermMeaningExample (string abcab)
TextThe long string being searched, length nA whole log file
PatternThe short string you look for, length mA search term
PrefixA piece cut from the fronta, ab, abc
SuffixA piece cut from the backb, ab, cab
BorderA proper substring that is both a prefix and a suffixab
OccurrenceA position where the pattern starts in the textA 0-based index
AlphabetThe set of possible charactersASCII, ACGT for DNA

A proper prefix is any prefix except the whole string. Borders are the heart of KMP, so it pays to get comfortable with them now.

Families of problems

Most string problems fall into four groups.

  • Single-pattern search: find every occurrence of one pattern. Naive matching, KMP, the Z-algorithm, Rabin-Karp and Boyer-Moore live here.
  • Multi-pattern search: find many patterns at once, such as a list of banned words. Aho-Corasick and Rabin-Karp with a hash set are the usual tools.
  • Dictionary lookup: find all words in a word list that start with a given prefix. The trie is the classic structure.
  • Text indexing: preprocess one text so that many queries run fast. Suffix arrays and FM-indexes cover this.

Naive matching

The obvious approach tries every starting position and compares character by character.

def naive_search(text: str, pattern: str) -> list[int]:
    n, m = len(text), len(pattern)
    hits = []
    for start in range(n - m + 1):
        j = 0
        while j < m and text[start + j] == pattern[j]:
            j += 1
        if j == m:
            hits.append(start)
    return hits


print(naive_search("abracadabra", "abra"))  # [0, 7]

For short inputs this is fine. But with text and pattern , almost all characters match at every position before failing, so the worst case is . The real problem is that each failure throws away what the comparisons just revealed and restarts from scratch at the next position. KMP stores that knowledge in a border table and reuses it; Rabin-Karp replaces most character comparisons with a hash comparison.

¿Tienes preguntas sobre este capítulo?
Capítulo siguienteHow It Works
aaaa...a
aaa...ab
m
O(n·m)

Computing borders by brute force

To build intuition, compute the longest border the slow way. The next chapter computes the same values for every prefix in O(m) with the prefix function.

def longest_border(s: str) -> int:
    for length in range(len(s) - 1, 0, -1):
        if s[:length] == s[-length:]:
            return length
    return 0


for word in ["abcab", "aaaa", "abcd", "ababa"]:
    print(word, longest_border(word))
# abcab 2 / aaaa 3 / abcd 0 / ababa 3

The longest border of ababa is aba, of length 3. Note that the prefix and the suffix may overlap.

When to write your own

Python's in, str.find, str.count and the re module are already highly optimized, so you will rarely rewrite KMP just to find a substring. Knowing the algorithms still matters when:

  • you need information the built-ins do not expose: prefix-function values, the smallest period of a string, all borders
  • the text arrives as a stream and cannot be passed in one piece
  • the task goes beyond a single search: many patterns, prefix lookup, substring hashing
  • you have to explain time complexity in a coding interview

A first Unicode caveat

What counts as one character is less obvious than it looks. A Python str is a sequence of code points, and one visible character may be several code points.

import unicodedata

a = "café"                       # single é (U+00E9)
b = "café"                 # e + combining acute accent (U+0301)
print(a == b, len(a), len(b))    # False 4 5
print(unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b))  # True
print(len(a.encode("utf-8")))    # 5 (bytes)

Unless text and pattern are normalized to the same form (for example NFC) before searching, words that look identical to a person will not match. The last chapter returns to this.

Summary

  • Text length is n, pattern length is m, and a border is a proper substring that is both a prefix and a suffix.
  • Naive matching is O(n·m) in the worst case because it discards what each failed attempt learned.
  • KMP and Z reuse earlier comparisons, Rabin-Karp compares hashes, and tries answer prefix queries over a dictionary.
  • For Unicode text, decide on normalization and on what a "character" is before you search.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.