Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a typical algorithm for finding a string within a string?

I recently had an interview question that went something like this:

Given a large string (haystack), find a substring (needle)?

I was a little stumped to come up with a decent solution.

What is the best way to approach this that doesn't have a poor time complexity?

like image 930
Courtney85 Avatar asked Mar 24 '10 01:03

Courtney85


People also ask

How will you locate a string within a string?

The IndexOf method returns the location of the first character of the first occurrence of the substring. The index is 0-based, which means the first character of a string has an index of 0. If IndexOf does not find the substring, it returns -1.

Which algorithm is used to find the string pattern?

Z algorithm is an algorithm for searching a given pattern in a string. It is an efficient algorithm as it has linear time complexity. It has a time complexity of O(m+n), where m is the length of the string and n is the length of the pattern to be searched.

What is the best string search algorithm?

Results: The Boyer-Moore-Horspool algorithm achieves the best overall results when used with medical texts. This algorithm usually performs at least twice as fast as the other algorithms tested. Conclusion: The time performance of exact string pattern matching can be greatly improved if an efficient algorithm is used.

What is a string in algorithm?

What is String? Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character '\0'.


1 Answers

I like the Boyer-Moore algorithm. It's especially fun to implement when you have a lot of needles to find in a haystack (for example, probable-spam patterns in an email corpus).

like image 123
Ether Avatar answered Sep 22 '22 05:09

Ether