TheAlgorithms / C-Plus-Plus

Collection of various algorithms in mathematics, machine learning, computer science and physics implemented in C++ for educational purposes.
https://thealgorithms.github.io/C-Plus-Plus
MIT License
30.08k stars 7.1k forks source link

feat: let KMP algorithm return index #2713

Closed Yancey2023 closed 2 weeks ago

Yancey2023 commented 2 weeks ago

Description of Change

For strings/knuth_morris_pratt.cpp:

fix: if pattern is empty, it should immediately return, otherwise pattern[k] will access out of bounds.

feat: let the KMP algorithm return index and add more tests.

Checklist

Notes:

realstealthninja commented 2 weeks ago

If you have the time could you write tests for this algorithm?

Yancey2023 commented 2 weeks ago

Hi, I've added some test cases! Additionally, I've changed the return value to the starting index of the pattern. Perhaps the usage of std::string::npos and size_t in the code might confuse beginners, but this is based on my reference to std::string::find(), which indeed returns a size_t type and returns std::string::npos when the substring is not found.

Yancey2023 commented 2 weeks ago

I don't understand:

#ifdef _MSC_VER
#include <string>  // use this for MS Visual C++
#else
#include <cstring>
#endif
Yancey2023 commented 2 weeks ago

I don't understand:

#ifdef _MSC_VER
#include <string>  // use this for MS Visual C++
#else
#include <cstring>
#endif

Why not just use #include <string>?

realstealthninja commented 2 weeks ago

It's old code feel free to remove

Yancey2023 commented 2 weeks ago

Thanks. I have deleted it.