Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java indexof(String str) method complexity [duplicate]

Tags:

Possible Duplicate:
What is the cost / complexity of a String.indexof() function call

What is the complexity of java indexof(String str) method. I mean there are String matching algorithms like KMP which runs in linear time. I am implementing a system that needs to search for large substring in a really large string,so can I use java indexof(String str) method or I should to implement KMP.

like image 221
alienCoder Avatar asked Oct 05 '12 18:10

alienCoder


People also ask

What is the time complexity of string indexOf?

indexOf() – also runs in linear time. It iterates through the internal array and checks each element one by one, so the time complexity for this operation always requires O(n) time.

What is the complexity of indexOf in Java?

The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string and pattern respectively.

Which is faster indexOf or contains Java?

Even if I switch the order of indexOf and contains, indexOf is still faster. In the benchmark i linked, the passed value is also alreday a string!

What is the value of STR indexOf Substr?

The indexOf() method returns the position of the first occurrence of substring in string. The first position in the string is 0. If the indexOf() method does not find the substring in string, it will return -1.


1 Answers

The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string and pattern respectively.

What you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing logical parts of the string which cannot match the pattern.

like image 162
Johan Sjöberg Avatar answered Sep 18 '22 15:09

Johan Sjöberg