Share my AC Java Solution


  • 0
    S

    Check it one by one until the "end" (index: String.length - needle.length)

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

Log in to reply
 

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