LeetCode - 28. Implement strStr()

14 篇文章 0 订阅
5 篇文章 0 订阅

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


思路与步骤:

两个字符串逐个字符比较,如果两个字符串第一个不同,则大的下标加1,小的不变,依次循环;

如果相同,则依次逐个比较后面的,全部相同则返回;如果不是全部相同,则小的下标重新设为0,大的在最开始的基础上前进1。

程序通过后,经过几次简化,最后写出了比较简洁的程序。


编程实现:

C程序:

int strStr(char* haystack, char* needle) {
    int hslen = strlen(haystack), nlen = strlen(needle);
    if(nlen == 0) return 0;
    if(nlen > hslen) return -1;
    
    int i=0, j=0;
    while (i <= hslen - nlen){
        if(haystack[i] != needle[j]) i++;
        else{
            while(haystack[i] == needle[j] && j < nlen-1){
                i++;
                j++;
            }
            if(j == nlen-1 && haystack[i] == needle[j])    return i-j;
            else{
                i = i-j+1;
                j = 0;
            }
        }
    }
    return -1;
}

Java程序:

public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.length() == 0) return 0;
        if(needle.length() > haystack.length()) return -1;
        
        char[] hsChar = haystack.toCharArray();
        char[] nChar = needle.toCharArray();
        int i=0, j=0;
        while (i <= haystack.length()-needle.length()){
            if((hsChar[i] != nChar[j])) i++;
            else{
                while(hsChar[i] == nChar[j] && j<needle.length()-1){
                    i++;
                    j++;
                }
                if(j==needle.length()-1 && hsChar[i] == nChar[j])    return i-j;
                else{
                    i = i-j+1;  //注意这里
                    j = 0;
                }
            }
        }
        return -1;
    }
}
别人的简洁的算法( 还没看)效率并没有很高:

public class Solution {
    public int strStr(String haystack, String needle) {
        //别人的简洁方法,未看
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                if (j == needle.length()) return i;
                if (i + j == haystack.length()) return -1;
                if (needle.charAt(j) != haystack.charAt(i + j)) break;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值