• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
草莓宝宝乖
博客园    首页    新随笔    联系   管理    订阅  订阅
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 }

 

 
posted on 2015-10-13 14:11  草莓宝宝乖  阅读(134)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3