LeetCode-Easy刷题 Implement strStr()

Posted 当以乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Easy刷题 Implement strStr()相关的知识,希望对你有一定的参考价值。

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

实现查找字符子串位置,未找到返回-1


//应该用KMP来做  
  public static int strStr(String haystack, String needle) 

        if(haystack ==null || needle ==null)
            return 0;
        
        if(haystack.length()<needle.length() )
            return -1;
        
        boolean isSuccess = true;
        for (int i = 0; i <= haystack.length() - needle.length(); i++) 

            for (int j = 0; j < needle.length(); j++) 
                if(haystack.charAt(i+j)!=needle.charAt(j))
                    isSuccess =false;
                    break;
                
            
            if(isSuccess)
                return i;
            else
                isSuccess = true;
            
        
        return -1;
    


以上是关于LeetCode-Easy刷题 Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Easy刷题 Valid Parentheses

LeetCode-Easy刷题(31) Single Number

LeetCode-Easy刷题 Remove Element

LeetCode-Easy刷题(19) Same Tree

LeetCode-Easy刷题(33) Min Stack

LeetCode-Easy刷题(33) Min Stack