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!

Recommended Answers

All 4 Replies

>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.

Thank you!

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.