DEV Community

Xavier Chretien
Xavier Chretien

Posted on

3 1

Day 5

Hello there

I hope you had a good weekend (and Monday) I didn't have the time to write the posts of this weekend but I did have the time to code...so there is day 5 !!

Details

  • Asked by: Dropbox
  • Difficulty: Hard

Problem

Implement an efficient string matching algorithm.

Given a string of length N and a pattern of length k, write a program that searches for the pattern in the string with less than O(N * k) worst-case time complexity.

If the pattern is found, return the start index of its location. If not, return False.

My solution

Nothing really special about this one. Sadly, because of the ".length" I'm not under O(N*k).

/**
 * Search pattern into searchIn
 *
 * @param searchIn 
 * @param pattern substring to find in searchIn
 * @return start index in string of the pattern, null if not found
 */
fun find(searchIn: String, pattern: String): Int? {
    for (i in 0 until searchIn.length - pattern.length){
        for ((index, c) in pattern.withIndex()){
            if (searchIn[i + index] != c)
                break
            else if(index == pattern.length - 1)
                return i
        }
    }
    return null
}
Enter fullscreen mode Exit fullscreen mode

Now I have a class, so see you tomorrow! ๐Ÿ˜ƒ

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

๐Ÿ‘ฅ Ideal for solo developers, teams, and cross-company projects

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay