前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >String - 28. Implement strStr()

String - 28. Implement strStr()

作者头像
ppxai
发布2020-09-23 17:15:59
3370
发布2020-09-23 17:15:59
举报
文章被收录于专栏:皮皮星球

28. 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 1:

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

Example 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().

思路:

返回子串在字符串中起始的索引,一般字符串匹配就是暴力匹配或者kmp,这里就直接匹配来做。

代码:

java:

代码语言:javascript
复制
class Solution {

    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) return 0;
        /*// 1. substring:
        for (int i = 0; i <= haystack.length() - needle.length(); i++)
            if (haystack.substring(i, i+needle.length()).equals(needle)) return i;
        return -1;
        */
        
        /*// 2. java api:
        return haystack.indexOf(needle);
        */

        // 3. java indexOf api source code:
        char first = needle.charAt(0);
        int max = (haystack.length() - needle.length());
        for (int i = 0; i <= max; i++) {
            // Look for first character.
            if (haystack.charAt(i) != first) {
                while (++i <= max && haystack.charAt(i) != first);
            }
            // Found first character, now look at the rest of value
            if (i <= max) {
                int j = i + 1;
                int end = j +  needle.length() - 1;
                for (int k = 1; j < end && haystack.charAt(j) == needle.charAt(k); j++, k++);
                if (j == end) {
                    // Found whole string.
                    return i;
                }
            }
        }
        return -1;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年06月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档