LeetCode—28. Implement strStr()

LeetCode—28. Implement strStr()

题目

https://leetcode.com/problems/implement-strstr/description/
给出两个字符串,needle和haystack,判断haystack中的子串能否和needle匹配,如果能,返回haystack子串的第一个字符的索引,否则返回-1.
在这里插入图片描述

思路及解法

1.暴力解法
自己先想了一个暴力的解法,设置两个指针,分别指向两个字符串,不断移动两个指针比较字符是否相等:如果相等,同时向右移动两个指针;如果不相等,将needle的指针重置为0,将haystack的指针指向上一次初始位置的下一个位置。最后判断needle的指针是不是指向了最后,用来确定字符串是不是完成了匹配。
查了资料之后发现了一个更为简洁的暴力解法的代码。参见下面的代码和注释。学习一波~
2.KMP算法(等我回来补。。)

代码

暴力解法1
class Solution {
    public int strStr(String haystack, String needle) {
        int hLen=haystack.length(), nLen=needle.length();
        if(nLen==0) return 0;
        int h=0, n=0;
        while(h<hLen && n<nLen){
            if(needle.charAt(n)==haystack.charAt(h)){
                n++;
                h++;
            }else{
                h=h-n+1;
                n=0;
            }
        }
        if(n!=nLen){
            return -1;
        }else{
            return h-nLen;
        }
    }
}
暴力解法2
class Solution {
    public int strStr(String haystack, String needle) {
        int hLen=haystack.length(), nLen=needle.length();
        if(nLen==0) return 0;
        for(int i=0; i<=hLen-nLen; i++){//变量i代表haystack指针的起始位置,
                     //也是haystack前面和needle不匹配的那一部分,注意终点不需要是hLen
            int j;
            for(j=0; j<nLen; j++){
                if(haystack.charAt(i+j)!=needle.charAt(j)){
                    break;
                }
            }
            if(j==nLen){
                return i;
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/pnnngchg/article/details/82945448