lc-28


//Implement strStr(). 
//
// Given two strings needle and haystack, return the index of the first occurren
//ce of needle in haystack, or -1 if needle is not part of haystack. 
//
// Clarification: 
//
// What should we return when needle is an empty string? This is a great questio
//n to ask during an interview. 
//
// For the purpose of this problem, we will return 0 when needle is an empty str
//ing. This is consistent to C's strstr() and Java's indexOf(). 
//
// 
// Example 1: 
//
// 
//Input: haystack = "hello", needle = "ll"
//Output: 2
// 
//
// Example 2: 
//
// 
//Input: haystack = "aaaaa", needle = "bba"
//Output: -1
// 
//
// 
// Constraints: 
//
// 
// 1 <= haystack.length, needle.length <= 104 
// haystack and needle consist of only lowercase English characters. 
// 
// Related Topics Two Pointers String String Matching 
// 👍 4350 👎 3748


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int strStr(String haystack, String needle) {
        int lh = haystack.length();
        int ln = needle.length();

        if (lh < ln) {
            return -1;
        }


        if (ln == 0) {
            return 0;
        }

        if (ln == lh) {
            if (haystack.equals(needle)) {
                return 0;
            } else {
                return -1;
            }
        }

        for (int i = 0; i <= lh - ln; i++) {
            String subStr = haystack.substring(i, i + ln);
            if (subStr.equals(needle)) {
                return i;
            }
        }

        return -1;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !