my java solution


  • 0
    C
    public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.equals(haystack))
            return 0;
        
        if(needle.length()>haystack.length())
            return -1;
        
        if(needle == "" || needle.length() == 0)
            return 0;
        
        int threshould = haystack.length()-needle.length();
        
        for(int i=0;i<=threshould;i++)
        {
            String sub= haystack.substring(i,i+needle.length());
            if(sub.equals(needle))
                return i;
            
        }
        
        return -1;
    }
    

    }


  • 0
    G

    Hi~I want to ask you a question.Can you tell me the differences between"needle == " " "and"needle.length() == 0 "?Aren't they the same meaning?Also I Think " needle == null"has the same meaning with them,but the result was wrong.Can you tell me why?Thanks a lot~


  • 0
    C

    Q1.
    if needle is " ", the length is 1 because there is a char space the ASCii code of which is 32.
    If needle is "", the length is 0 because it contains nothing at all.
    You can find that they are not the same thing.

    Q2.
    if needle is "", it takes one address in the storage.
    if needle is null, it doesn't take any address in the storage.

    Best,
    Jingwei


  • 0
    G

    @ChairmanMao Your explanation is very clear.Thanks a lot!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.