Implement strStr() 实现strStr函数 @ LeetCode

本文深入探讨了实现strStr()函数的方法,包括使用indexOf、O(n^2)暴力匹配以及更高效的KMPO(n)算法。通过实例代码,详细解析了如何在字符串中查找子串,并注意到了输入检测和越界问题的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

实现strStr() 函数


经典题目!练习必做到bug free题

思路:

1.用indexOf找到第一次出现的index,如果找到则调用substring,否则返回null ==> 因为用到了indexOf,所以面试时候肯定不可以

2.用O(n2)的暴力匹配(推荐)

3 KMP O(n), 面试时一般不会要求写出

/**
 * Implement strStr().
 * 
 * Returns a pointer to the first occurrence of needle in haystack, or null if
 * needle is not part of haystack.
 * 
 */
public class S28 {

	public static void main(String[] args) {
		String haystack = "testing test";
		String needle = "test";
		System.out.println(strStr(haystack, needle));
	}
	
	public static String strStr(String haystack, String needle) {
		// 找到出现第一次的index
        int idx = haystack.indexOf(needle);
        if(idx < 0){		// 没找到
        	return null;
        }else{			// 利用index得到substring
        	return haystack.substring(idx);
        }
    }

}



值得注意的几点:

1 输入检测

2 越界检测

public class Solution {
    public String strStr(String haystack, String needle) {
        if(haystack==null || needle==null || needle.length()>haystack.length()){
            return null;
        }
        int i=0, j=0;
        for(i=0; i<=haystack.length()-needle.length(); i++){    // Notice <= here!
            for(j=0; j<needle.length(); j++){
                if(haystack.charAt(i+j) != needle.charAt(j)){
                    break;
                }
            }
            if(j == needle.length()){
                return haystack.substring(i);
            }
        }
        return null;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值