Leecode28 implement-strstr

题目描述

实现函数 strStr。
函数声明如下:
char *strStr(char *haystack, char *needle)

分析

直接匹配

java 代码

public class Solution {
    public String strStr(String haystack, String needle) {
        if(haystack == null || needle == null || needle.length() ==0){
            return haystack;
        }
        if(haystack.length() < needle.length()){
            return null;
        }
        for(int i = 0; i< haystack.length();i++){
            int j = i;
            int k = 0;
            while(j < haystack.length()&& k < needle.length() &&haystack.charAt(j) == needle.charAt(k)){
                j++;
                k++;                
            }
            if(k >=  needle.length()){
                return haystack.substring(i);
            }
        }
        return null;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容