028 Implement strStr()

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example:

Input: haystack = "hello", needle = "ll"
Output: 2

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

解释下题目:

实现java的indexOf()方法

1. 挨个判断

实际耗时:6ms

public int strStr(String haystack, String needle) {
        if (needle.equals("") || null == needle) {
            return 0;
        }

        //最多循环haystack.length() - needle.length()次
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            int now = i; //记录目前的haystack中的索引
            int count = 0; //匹配上的个数
            for (int j = 0; j < needle.length(); j++) {
                if (haystack.charAt(now) != needle.charAt(j)) {
                    break;
                } else {
                    count++;
                    now++;
                }
                if (count == needle.length()) {
                    return i;
                }
            }
        }
        return -1;
    }

  思路:那除了挨个判断还能怎么做呢?

时间复杂度O(nm) n和m分别为两个数组的长度
空间复杂度O(1)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 口语开不了口?这里有答案(干货) 中国学生面对口语的心态,有点像宅男面对女神 明明很上心,却不敢靠近 偶尔壮胆前进...
    peter潘英语阅读 225评论 0 0
  • 今天在家看《演说家是怎样炼成的》的书籍,给我印象最深的一句话就是:演讲一定得真情流露,具象、对比、放大。 言简意赅...
    林亦凡阅读 448评论 0 0
  • 满井游记(节选) 袁宏道 燕地寒,花朝节后,余寒犹厉。冻风时作,作则飞沙走砾。局促一室之内,欲出不得。每冒风驰行...
    墫壿与祇祗衹袛阅读 862评论 0 0
  • 忙碌了两天,终于迎来熊孩子们报到,昨天通知她们在小操场先集合,再统一到教室,早上8:25到校门口去看他们,马...
    春夏AI阅读 270评论 0 1