Implement strStr(leetcode28)

本文详细介绍了如何使用暴力法解决字符串匹配问题,并通过示例代码解释了算法的实现过程。文章涵盖了一些常见场景,如空字符串、不匹配长度、多重复现以及长字符串比较等,确保代码在各种情况下的正确性和效率。

 

O(nm) runtime, O(1) space – Brute force:

There are known efficient algorithms such as Rabin-Karp algorithm, KMP algorithm, or the Boyer-Moore algorithm. Since these algorithms are usually studied in an advanced algorithms class, it is sufficient to solve it using the most direct method in an interview – The brute force method.

The brute force method is straightforward to implement. We scan the needle with the haystack from its first position and start matching all subsequent letters one by one. If one of the letters does not match, we start over again with the next position in the haystack.

Assume that n = length of haystack and m = length of needle, then the runtime complexity is O(nm).

Have you considered these scenarios?

1. needle or haystack is empty. If needle is empty, always return 0. If haystack is empty, then there will always be no match (return –1) unless needle is also empty which 0 is returned.

2. needle’s length is greater than haystack’s length. Should always return –1. needle is located at the end of haystack. For example, “aaaba” and “ba”. Catch

possible off-by-one errors.
3. needle occur multiple times in haystack. For example, “mississippi” and “issi”. It should return index 2 as the first match of “issi”.

4. Imagine two very long strings of equal lengths = n, haystack = “aaa...aa” and needle = “aaa...ab”. You should not do more than n character comparisons, or else your code will get Time Limit Exceeded in OJ. 

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3         for(int i = 0; ; i++) {
 4             for(int j = 0; ;j++) {
 5                 if(j == needle.length()) return i;
 6                 if(i+j == haystack.length()) return -1;
 7                 if(needle.charAt(j) != haystack.charAt(i+j)) break;
 8             }
 9         }
10     }
11 }

 

 

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4874486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值