Implement strStr()

Implement strStr()

https://leetcode.com/problems/implement-strstr/

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

算法思想:

1)定义两个Pointers:i和j,i初始化为指向haystack的的第一个元素;j初始化为指向needle的第一个元素

2)i的范围是从0到两个string的长度的差值,j的范围是0到needle的长度;

3)判断i指向的元素和j指向的元素(这里是j为0指向的,即第一个元素)是否相等,如果不等,i继续向后移动;如果相等,就比较i后面的元素是否和j指向的所有元素是否相等,相等就返回这个i;如果不相等,i继续向后移动

程序代码:


public class Solution {

    public int strStr(String haystack, String needle) {

        int lenHay = haystack.length();

        int lenNee = needle.length();

        if (haystack == null || needle == null || lenHay < lenNee) {

            return -1;

        }

        if (needle.isEmpty()) {

            return 0;

        }

        

        int lenDiff = lenHay - lenNee;

        for (int i = 0; i <= lenDiff; i++) {

            if (haystack.charAt(i) == needle.charAt(0)) {

                int j = 1;

                while(j < lenNee) {

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

                        break;

                    }

                    j++;

                }

                if (j == lenNee) {

                    return i;

                }

            }

        }

        return -1;

    }

}

posted @ 2015-08-20 18:27  TinaYo  阅读(215)  评论(0编辑  收藏  举报