Share my easy Java solution


  • 0
    B

    public class Solution {
    public int strStr(String haystack, String needle) {
    //require
    if(haystack==null||needle==null)
    return -1;
    int size1=haystack.length(),size2=needle.length();
    if(size2==0)
    return 0;
    if(size1<size2)
    return -1;
    //variant
    int ans=-1;
    for(int i=0;i<size1-size2+1;i++)
    if(haystack.substring(i,i+size2).equals(needle)){
    ans=i;
    break;
    }
    //ensure
    return ans;
    }
    }


Log in to reply
 

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