• [LeetCode] 28. Implement strStr() 实现strStr()函数


    Implement strStr().

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

    Example 1:

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

    Example 2:

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

    在一个字符串中找另一个字符串第一次出现的位置。

    解法2:从第1个字母开始循环,检查由当前字母s[i]到s[i+len(needle)]是否等于needle。T: O(n * k), S: O(k)

    解法2:Knuth-Morris-Pratt字符串查找算法(简称为KMP算法)可在一个主文本字符串S内查找一个词W的出现位置。T: O(n + k), S: O(k)

    Java:

    public int strStr(String haystack, String needle) {
      for (int i = 0; ; i++) {
        for (int j = 0; ; j++) {
          if (j == needle.length()) return i;
          if (i + j == haystack.length()) return -1;
          if (needle.charAt(j) != haystack.charAt(i + j)) break;
        }
      }
    }
    

    Java:

    public class Solution {
        public int strStr(String haystack, String needle) {
            int l1 = haystack.length(), l2 = needle.length();
            if (l1 < l2) {
                return -1;
            } else if (l2 == 0) {
                return 0;
            }
            int threshold = l1 - l2;
            for (int i = 0; i <= threshold; ++i) {
                if (haystack.substring(i,i+l2).equals(needle)) {
                    return i;
                }
            }
            return -1;
        }
    }  

    Python: T: O(n*k)

    class Solution(object):
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            for i in xrange(len(haystack) - len(needle) + 1):
                if haystack[i : i + len(needle)] == needle:
                    return i
            return -1
    

    Python: KMP, T: O(n + k)

    class Solution(object):
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            if not needle:
                return 0
    
            return self.KMP(haystack, needle)
    
        def KMP(self, text, pattern):
            prefix = self.getPrefix(pattern)
            j = -1
            for i in xrange(len(text)):
                while j > -1 and pattern[j + 1] != text[i]:
                    j = prefix[j]
                if pattern[j + 1] == text[i]:
                    j += 1
                if j == len(pattern) - 1:
                    return i - j
            return -1
    
        def getPrefix(self, pattern):
            prefix = [-1] * len(pattern)
            j = -1
            for i in xrange(1, len(pattern)):
                while j > -1 and pattern[j + 1] != pattern[i]:
                    j = prefix[j]
                if pattern[j + 1] == pattern[i]:
                    j += 1
                prefix[i] = j
            return prefix  

    C++:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if (needle.empty()) return 0;
            int m = haystack.size(), n = needle.size();
            if (m < n) return -1;
            for (int i = 0; i <= m - n; ++i) {
                int j = 0;
                for (j = 0; j < n; ++j) {
                    if (haystack[i + j] != needle[j]) break;
                }
                if (j == n) return i;
            }
            return -1;
        }
    };
    

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    Android SDK 在线更新镜像服务器
    Android Studio (Gradle)编译错误
    java ZIP压缩文件
    java文件操作(输出目录、查看磁盘符)
    JXL读取写入excel表格数据
    Linux命令zip和unzip
    Linux查看系统基本信息
    Ubuntu C++环境支持
    Linux开机执行bash脚本
    ubuntu中磁盘挂载与卸载
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8555914.html
Copyright © 2020-2023  润新知