LeetCode -- Implement strStr()

Question:

Implement strStr().

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

Analysis:

实现strStr()函数,

返回在字符串hayStack中第一次出现needle的位置,如果在haystack中没有出现,则返回-1。

思路:

挨个字符往下比较,如果当前比较过程中出现一个不等的情况,则break此次循环,往下走一个字符。

未考虑的情况:

1. needle的长度大于haystack的长度;

2. 没有考虑比较时,i的越界情况。

Answer:

public class Solution {
    public static int strStr(String haystack, String needle) {
        if(haystack.length() < needle.length())
                return -1;
        if(haystack.length() == 0)
                return 0;

        char[] ch1 = haystack.toCharArray();
        char[] ch2 = needle.toCharArray();
        for(int i=0; i<=ch1.length - ch2.length; i++) {
                int j = 0;
                for(; j<ch2.length; j++) {
                    if(ch1[i+j] != ch2[j])
                        break;
                }
                if(j == ch2.length)
                    return i;
        }
        return -1;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4943061.html