【LeetCode从零单排】No28 Implement strStr()

简介: 题目Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.代码public class Solution { public int strStr(String haystack,

题目

Implement strStr().

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

代码

public class Solution {
    public int strStr(String haystack, String needle) {
        if( needle.length()==0) return 0;
        if(haystack.length()==0 ) return -1;
        char[] haystack_char=haystack.toCharArray();
        char[] needle_char=needle.toCharArray();
        
        for(int i=0;i<haystack_char.length;i++){
        	a:
            if(haystack_char[i]==needle_char[0]){
             if(haystack_char.length-i>=needle_char.length){    
                for(int j=0;j<needle_char.length;j++){
                    
                      if(haystack_char[i+j]!=needle_char[j]){
                    	    
                        break a;
                      }
                        
                    }
                   
                
                return i;
                
              }
              else{
                   return -1;
               }
            }
        }
        return -1;
        
    }
}


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/




目录
相关文章
|
8月前
|
算法
LeetCode-28 实现strStr() KMP算法的学习
LeetCode-28 实现strStr() KMP算法的学习
|
10月前
|
算法 安全 Java
LeetCode - #28 实现 strStr()
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
|
10月前
|
算法 Java C语言
leetcode:28.实现strStr()
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
44 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
60 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
|
Java C语言
LeetCode 28. 实现 strStr()
实现 strStr() 函数。
73 0
|
存储 前端开发 算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
132 0
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
LeetCode 225. Implement Stack using Queues
使用队列实现栈的下列操作: push(x) -- 元素 x 入栈; pop() -- 移除栈顶元素; top() -- 获取栈顶元素; empty() -- 返回栈是否为空
56 0
LeetCode 225. Implement Stack using Queues
|
存储 算法 索引
代码随想录刷题|LeetCode KMP算法理论 28. 实现 strStr() 459.重复的子字符串
代码随想录刷题|LeetCode KMP算法理论 28. 实现 strStr() 459.重复的子字符串
代码随想录刷题|LeetCode KMP算法理论 28. 实现 strStr() 459.重复的子字符串
leetcode【字符串—简单】28.实现 strStr()
leetcode【字符串—简单】28.实现 strStr()
leetcode【字符串—简单】28.实现 strStr()
|
存储 算法 Java
LeetCode 27移除元素&28实现strStr()&29两数相除
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
77 0
LeetCode 27移除元素&28实现strStr()&29两数相除