• [LeetCode] 28. Implement strStr()


    Implement strStr().

    Return the index of the first occurrence 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 question to ask during an interview.

    For the purpose of this problem, we will return 0 when needle is an empty string. 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
    

    Example 3:

    Input: haystack = "", needle = ""
    Output: 0

    Constraints:

    • 0 <= haystack.length, needle.length <= 5 * 104
    • haystack and needle consist of only lower-case English characters.

    实现strStr()函数。

    题意是给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。这个题有KMP算法的答案但是我这里只给出另一个简单的解法,不算暴力解。

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {string} haystack
     3  * @param {string} needle
     4  * @return {number}
     5  */
     6 var strStr = function (haystack, needle) {
     7     // corner case
     8     if (needle === '') {
     9         return 0;
    10     }
    11 
    12     if (needle.length > haystack.length) {
    13         return -1;
    14     }
    15 
    16     // normal case
    17     let m = haystack.length;
    18     let n = needle.length;
    19     for (let i = 0; i < m - n + 1; i++) {
    20         if (haystack.substring(i, i + n) === needle) {
    21             return i;
    22         }
    23     }
    24     return -1;
    25 };

    Java实现

     1 class Solution {
     2     public int strStr(String haystack, String needle) {
     3         // corner case
     4         if (needle == null || needle.length() == 0) {
     5             return 0;
     6         }
     7 
     8         if (needle.length() > haystack.length()) {
     9             return -1;
    10         }
    11 
    12         // normal case
    13         int m = haystack.length();
    14         int n = needle.length();
    15         for (int i = 0; i < m - n + 1; i++) {
    16             if (haystack.substring(i, i + n).equals(needle)) {
    17                 return i;
    18             }
    19         }
    20         return -1;
    21     }
    22 }

    LeetCode 题目总结

  • 相关阅读:
    【js】栈方法和队列方法
    adb devices 不能连接设备 could not install *smartsocket* listener
    mysql无法启动服务,错误1067
    Sql Server存储过程详解
    ef not in
    checkbox多选框取值
    Linq 常用操作(增删改)
    二进制与图片相互转换
    jQuery 二级联动
    百度地图API功能
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12381388.html
Copyright © 2020-2023  润新知