美文网首页Leetcode 简单
LeetCode Simple_28 实现strStr()

LeetCode Simple_28 实现strStr()

作者: 天才一般的幼稚 | 来源:发表于2020-01-12 10:27 被阅读0次

    问题描述

    实现 strStr() 函数。
    给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

    示例

    输入: haystack = "hello", needle = "ll"
    输出: 2
    输入: haystack = "aaaaa", needle = "bba"
    输出: -1

    思路

    第一秒KMP,第二秒不会写……hhhhh。与上题一样,利用双指针进行循环匹配,效率上肯定不如KMP算法高效。外循环的索引表示将要匹配的子串在原字符串中的起始位置,内循环的索引表示匹配子串的位置。不使用内外索引均表示字符串起始位置,这样做是为了避免子串比原串长导致误判的情况。如:haystack = "aaaa", neddle = "aaaaaaa"。简单题老老实实双指针,KMP学了没啥用

    //报错的代码
    class Solution {
        public int strStr(String haystack, String needle) {
            if(needle.equals("")){
                return 0;
            }
            for(int i=0; i<haystack.length(); i++){
                int j=0;
                for(; j<needle.length(); j++){
                    if(haystack.charAt(i) != needle.charAt(j)){
                        break;
                    }else {
                        continue;
                    }
                }
                if(j == needle.length()){
                    return i;
                }
            }
            return -1;
        }
    }
    //成功执行的代码
    class Solution {
        public int strStr(String haystack, String needle) {
            int hLength = haystack.length(), nLength = needle.length();
            for(int i = 0; i < hLength-nLength+1; i ++){
                int j=0;
                for(; j < nLength; j++){
                    if(haystack.charAt(i+j) != needle.charAt(j)){
                        break;
                    }
                }
                if(j == nLength){
                    return i;
                }
            }
            return -1;
        }
    }
    

    相关文章

      网友评论

        本文标题:LeetCode Simple_28 实现strStr()

        本文链接:https://www.haomeiwen.com/subject/xpyiactx.html