Using substring API simple Java Solution. But not sure why failing at test case "a", "a"

  • 1

    Not sure why my solution is failing. It works fine in eclipse and gives the correct result 0 for the testcase "a","a". But while running it in ojleetcode it return -1. Please help!

    public int strStr(String haystack, String needle) {
        if(haystack==needle || needle.length()==0){
           return 0;
       if(needle.length() > 0){
               for(int i=0;i<haystack.length() - needle.length()  ;i++){
                   int size = needle.length();
                   if(haystack.substring(i,i+size) == needle){
                       return i;
       return -1;

  • 0

    When comparing two objects in java, you should use Object.equals(Object) instead of '=='.
    Strings are objects, so '==' compares not their content but their address.

Log in to reply

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