What is the cost / complexity of a String.indexOf() function call

后端 未结 3 1104
闹比i
闹比i 2020-12-09 11:38

What is the cost / complexity of a String.indexOf() function call?

相关标签:
3条回答
  • 2020-12-09 12:06

    Depends on the implementation.

    For example, when searching for a string within a longer string, "The Turbo Boyer-Moore algorithm takes an additional constant amount of space to complete a search within 2n comparisons (as opposed to 3n for Boyer-Moore), where n is the number of characters in the text to be searched." (see Wikipedia).

    0 讨论(0)
  • 2020-12-09 12:07

    In java, if the call is string1.indexOf(string2) the time cost would be O(m - n) where m is the length of string1 and n is the length of string2.

    0 讨论(0)
  • 2020-12-09 12:18

    IIRC Java's implementation of .indexOf() is just the naive string matching algorithm, which is O(n+m) average and O(n*m) worst case.

    In practice this is fast enough; I tested it for relatively large needle (>500 char) and haystack (few MB) strings and it would do the matching in under a second (in an average household computer). Mind you I forced it to go through the whole haystack.

    0 讨论(0)
提交回复
热议问题