Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

在 O(n^2) 时间内找到给定字符串的所有子字符串。

Posted on 2022-05-29

rf7h2wf7jbfevbi7c55n.png

下面是用 JavaScript 编写的程序员,以O(N^2)时间复杂度和额外O(1)空间查找给定字符串的所有可能子字符串;

程序

function genSubstrings ( inputString ){ debugger ; let resultArray = []; // outer loop to run n times [n = size of string] for ( let i = 0 ; i < inputString . length ; i ++ ){ // pushing first char of string as substring // as we know that each char will be substring itself too. resultArray . push ( inputString [ i ]); // inner loop to run n - 1 times; for ( let j = i + 1 ; j < inputString . length ; j ++ ){ // get last substring and append the new next char resultArray . push ( resultArray [ resultArray . length - 1 ] + inputString [ j ] ); } } return resultArray ; }

输出

genSubstrings ( " abcd " ); ( 10 ) [ ' a ' , ' ab ' , ' abc ' , ' abcd ' , ' b ' , ' bc ' , ' bcd ' , ' c ' , ' cd ' , ' d ' ]

我在互联网上搜索了一个更好的解决方案,它可以在小于 O(N^2) 的时间复杂度内运行,但没有找到。

如果有人有更好的解决方案,请在评论中写下,这将非常有帮助。

缩略图取自geekforgeek

原文: https://dev.to/rajeshroyal/find-all-substring-of-a-given-string-in-on2-time-2ip7

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Elad Gil
  • Ellie Huxtable
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Lou Plummer
  • Luke Wroblewski
  • Matt Stoller
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • Sam Rose
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • thesephist
  • Thinking Deep & Wide
  • Tim Kellogg
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme