• 实现 strStr() 函数-算法刷题


    算法题目

    实现 strStr() 函数:

    给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的
    第一个位置 (从0开始)。如果不存在,则返回 -1。

    示例 1:

    输入: haystack = "hello", needle = "ll"
    输出: 2
    

    示例 2:

    输入: haystack = "aaaaa", needle = "bba"
    输出: -1
    

    说明:
    当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
    对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的
    indexOf() 定义相符

    /**
    
    @author cosefy
    
    @date 2020/7/2
    */
    public class StrStr {
    public static void main(String[] args) {
        String haystack = "aaaba";
        String needle = "sssssss";
        int res1 = test1(haystack, needle);
        System.out.println(res1);
    }
    
    //解法一
    /*
    思路:1,判断模式串是否为空,空则返回0,判断模式串的长度是否大于主串,大于则返回-1.
         2,如果子串和主串第一个字符不相同则直接向后移动主串
         3,如果部分匹配,则需要主串回退,此处可以利用一个辅助变量代替主串前进,可以省略回退。
     */
    private static int test1(String haystack, String needle) {
        int n = needle.length();
        if (n == 0)
            return 0;
        int h = haystack.length();
        if (n > h)
            return -1;
        for (int i = 0; i < h - n + 1; i++) {
            int temp = i, j = 0;   //利用temp变量来代替主串元素往后比较,可以省略匹配失败后主串的回退
            for (; j < n; j++) {
                if (haystack.charAt(temp++) != needle.charAt(j))
                    break;
            }
            if (j == n) //第二个for循环完全执行完之后j=n,说明完全匹配。
                return i;
        }
        return -1;
    
    
    ​    }
    
    ​    //解法二:KMP算法
    }
    
  • 相关阅读:
    实时需要分析
    .NET 单元测试的艺术&单元测试之道C#版
    代码演示C#各2.0到8.0版本[FK,2.0-4.8.0]
    微软Visual Studio Code 0.8.0发布,新增多种主题
    ASP.NET 5 Beta 7 版本
    软件开发设计原则
    Immutable(不可变)集合
    使用Hystrix提高系统可用性
    微软发布 Windows Server 2016 预览版第三版,开发者要重点关注Nano Server
    Akka.NET v1.0 已发布,支持Mono
  • 原文地址:https://www.cnblogs.com/cosefy/p/13226644.html
Copyright © 2020-2023  润新知