TypechoJoeTheme

IT技术分享

统计

[LeetCode 28] Implement strStr() [Java]

2017-11-25
/
0 评论
/
818 阅读
/
正在检测是否收录...
11/25

1. Description

Implement strStr().

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

2. Example

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

3. Code

import java.util.HashMap;
import java.util.Map;

public class LeetCode0028 {
    public int strStr(String haystack, String needle)
    {
        if (haystack == null || needle == null || haystack.length() < needle.length()) {
            return -1;
        }
        if (needle.length() == 0) {
            return 0;
        }

        Map map = getShift(needle);

        int maxLength = haystack.length() - needle.length();

        for (int i = 0; i <= maxLength;) {
            int j = 0;
            for (; j < needle.length(); j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
            }
            if (j == needle.length()) {
                return i;
            }
            i += needle.length();
            if (i < haystack.length()) {
                i -= map.getOrDefault(haystack.charAt(i), -1);
            }
        }
        return -1;
    }

    private Map getShift(String needle)
    {
        Map map = new HashMap();
        for (int i = 0; i < needle.length(); i++) {
            map.put(needle.charAt(i), i);
        }
        return map;
    }

    public static void main(String[] args)
    {
        LeetCode0028 leetcode = new LeetCode0028();
        System.out.println(leetcode.strStr("hello", "ll"));
    }
}
String
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1289/(转载时请注明本文出处及文章链接)