zoukankan      html  css  js  c++  java
  • 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.

    Example 1:

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

    Example 2:

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

    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().

    用substring()来判断

    注意:Java 7中,string.substring()的时间复杂度是O(n),n为子串长度

    time: O(mn), space: O(1)  -- m: needle length, n: haystack length

    class Solution {
        public int strStr(String haystack, String needle) {
            if(haystack == null || needle == null) return -1;
            if(haystack.length() < needle.length()) return -1;
            if(needle.length() == 0) return 0;
            
            int m = needle.length();
            for(int i = 0; i <= haystack.length() - m; i++) {
                if(haystack.substring(i, i + m).equals(needle))
                    return i;
            }
            return -1;
        }
    }
  • 相关阅读:
    valueOf与toString
    责任链模式
    Js中Symbol对象
    Vue路由懒加载
    updatedb命令
    策略模式
    Docker(3)- Centos 7.x 下 Docker 镜像加速配置
    Vmware
    Docker(2)- Centos 7.x 下安装 Docker
    Docker(1)- 什么是 Docker
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10133131.html
Copyright © 2011-2022 走看看