Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

分析,找字符串haystack中最先出现字符串needle的位置,需要注意的是字符串可能为""的情况的处理


public class Solution {

    public int strStr(String haystack, String needle) {

        if(needle.equals(""))

            return 0;

        int hl=haystack.length();

        int nl=needle.length();

        //if(hl==nl)

        int j=0;

        int i=0;

        for(i=0;i<hl-nl+1;i++)

        {

            for(j=0;j<nl;j++)

                if(haystack.charAt(i+j)!=needle.charAt(j))

                    break;

            if(j==nl)

                return i;

        }

        return -1;

    }

}