• 字符串查找 · Implement strStr()


    [抄题]:

    对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1

    如果 source = "source" 和 target = "target",返回 -1

    如果 source = "abcdabcdefg" 和 target = "bcd",返回 1

     [暴力解法]:

    时间分析:

    空间分析:

    [思维问题]:

    自己知道大概什么意思,但是不敢写。下次要进入写代码阶段

    [一句话思路]:

    1. 双重for时,用i+j和j 比较,从而找到符合条件的i,头一次见
    2. for循环在不知道上限的时候也可以不写,头一次见

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    1. 先找到起点i,确认可以走。然后讨论j 走完、走完两种情况。

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    for (int i = 0; ; i++) {
                for (int j = 0; ; j++) {
                    if (j == needle.length()) return i;//j finished
                    if (i+j == haystack.length()) return -1;//i finished but j not finished
                    if (haystack.charAt(i + j) != needle.charAt(j)) break;
    charAt(i + j) != charAt(j)

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int strStr(String haystack, String needle) {
            //corner case
            if (needle == null || haystack == null) {
                return -1;
            }
            //find, not find, not equal
            for (int i = 0; ; i++) {
                for (int j = 0; ; j++) {
                    if (j == needle.length()) return i;//j finished
                    if (i+j == haystack.length()) return -1;//i finished but j not finished
                    if (haystack.charAt(i + j) != needle.charAt(j)) break;
                }
            }
        }
    }
    View Code
  • 相关阅读:
    在一个tomcat中配置多个tomcat服务器 111
    同一个tomcat部署多个项目11
    Tomcat部署多个项目及相关配置
    同一个tomcat部署多个项目
    Tomcat下部署多个项目
    Linux环境下在Tomcat上部署JavaWeb工程
    Linux命令详解之—pwd命令
    PWD
    C语言内存分配
    每天小练笔10-小和尚挑水(回溯法)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8542279.html
Copyright © 2020-2023  润新知