Leetcode exercises Implement strStr ()

Description Title (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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Base solution

In this problem, strStr function is to return the position of the first matching string appears. In java, among them, a function is provided for this feature. That is IndexOf

indexOf return value int

If found, return to find the characters starting character position index index (starting at 0).

If not found, returns -1

Refer to the following:


public class containString
{
    public static void main(String[] args)
    {
        String str1 = "sdfsfsfa2we";
        String str2 = "we";

        String str3 = "me";

        System.out.println(str1.indexOf(str2));
        System.out.println(str1.indexOf(str3));
    }
}

So, you can directly use indexOf implement this feature functions.

Code optimization

In addition, we can also optimize the code, refer others to the solution. Implement this feature.

Is the use of an iterative loop, and then using the method of comparing the judgment value, until it finds and needle equal array, returns the coordinates. Otherwise index = -1

class Solution {
    public int strStr(String haystack, String needle) {
      
    if(needle.length()==0)
    {
        return 0;
    }   
        
    int index = -1;
    
    for(int i=0;i<=haystack.length()-needle.length();i++)
    {
        if(haystack.charAt(i)==needle.charAt(0))
        {
            if(haystack.substring(i,i+needle.length()).equals(needle))
            {
                return i;
            }
        }
        
    }
        
    return index;
       
    
    }
}

Guess you like

Origin www.cnblogs.com/zhichun/p/12129346.html