Leet Code OJ 28. Implement strStr() [Difficulty: Easy]

题目:

Implement strStr().

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

翻译:

实现一个方法strStr()。返回字符串needle第一次在字符串haystack出现的下标,如果needle不是haystack的一部分,就返回-1。

分析:

在文本中查找某个模式出现的位置的算法,称为字符串匹配算法。常用的方法有朴素字符串匹配算法、KMP算法等。朴素字符串匹配算法,就是把2个字符串头部对齐,然后逐一字符匹配,失配后,把needle右移一位,继续从头匹配。我们这里采用KMP算法。

代码:

public class Solution {
    /**
     * 改进的Next指针算法
     *
     * @param s
     * @return
     */
    private int[] getNext(String s) {
        int[] next = new int[s.length()];
        next[0] = 0;
        if (s.length() == 1) {
            return next;
        }
        next[1] = 0;
        int i = 1;
        int j = 0;
        while (i < s.length() - 1) {
            if (s.charAt(i) == s.charAt(j)) {
                j++;
                i++;
                if (s.charAt(i) == s.charAt(j)) {
                    next[i] = next[j - 1];
                } else {
                    next[i] = j;
                }
            } else {
                if (j == 0) {
                    i++;
                    next[i] = 0;
                } else {
                    j = next[j];
                }
            }
        }
        return next;
    }
    /**
     * KMP字符串匹配算法
     *
     * @param s
     * @return
     */
    public int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int[] next = getNext(needle);
        int index = -1;
        int i = 0;
        int j = 0;
        while (i < haystack.length()) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                if (j == needle.length() - 1) {
                    return i - j;
                }
                i++;
                j++;
            } else {
                if (j == 0) {
                    i++;
                } else {
                    j = next[j];
                }
            }
        }
        return index;
    }
}
时间: 2024-08-08 21:27:18

Leet Code OJ 28. Implement strStr() [Difficulty: Easy]的相关文章

Leet Code OJ 338. Counting Bits [Difficulty: Easy]

题目: Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is v

Leet Code OJ 189. Rotate Array [Difficulty: Easy]

题目: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve thi

Leet Code OJ 66. Plus One [Difficulty: Easy]

题目: Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 翻译: 给定一个非负数,它是有数字的数组组成,把这个非负数+1. 这个非负数的存储方式,是把最高有效位数字放到列表的前面. 分析: 首先考虑的是

Leet Code OJ 1. Two Sum [Difficulty: Easy]

题目: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1]

Leet Code OJ 27. Remove Element [Difficulty: Easy]

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 翻译: 给定一个数组和一个值,在原地移除所有的这个值的实例,并且返回新的数组长度. 元素的顺序可以被改变.

Leet Code OJ 223. Rectangle Area [Difficulty: Easy]

题目: Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. Assume that the total area is never beyond the maximum possible value of int

Leet Code OJ 344. Reverse String [Difficulty: Easy]

题目: Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". 翻译: 写一个函数,使用字符串作为输入,返回它反转后的结果. 例如,输入"hello",返回"olleh". 分析: 转为字符数组后,将第一个字符和最后一个字符对调,第二个字符

Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]

题目: Given a string containing just the characters , determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 翻译: 给定一个字符串,只包含'

28. Implement strStr()【easy】

28. Implement strStr()[easy] Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 解法一: 1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 if (haystack