954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to optimize this function(about pattern match,A problem in a Interview)

Question is :
Write a function

int f(char* str, long pattern)


to find out how many pattern does the str contain? str is a char array consist of '1' and '0';
for example: str = "11010101110101011110100011001" ,pattern = 110;

My solution is change pattern and str to std::string, then use std::string::find to search.
but I think this solution is not efficient.

1.Could you tell me other efficient solution? thanks.

2. if the second parameter is a array, how to optimize it?

Thank you very much!

littlestone
Light Poster
42 posts since Mar 2008
Reputation Points: 14
Solved Threads: 6
 

>but I think this solution is not efficient.
Why? If you're just guessing or using your "programmer's intuition", you're probably wrong. Interviewers (good ones) tend to smile more on people who aren't afraid to say "I'd rather optimize clean, correct code than fix fast code". That's the sign of an experienced programmer.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Thank you!

I don't know the answer of the second question: if pattern is a array, how to optimize it?

littlestone
Light Poster
42 posts since Mar 2008
Reputation Points: 14
Solved Threads: 6
 

>I don't know the answer of the second question:
>if pattern is a array, how to optimize it?
The answer is the same.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

if the pattern matching is done on a very long sequence of characters (eg. searching for the occurrence of a particular phrase or word in a large book), there are several interesting algorithms. here is a link that explores some of them. http://www.jea.acm.org/ARTICLES/Vol4Nbr2/index.html

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You