当前位置: 首页 > article >正文

面试经典150题——Day23

文章目录

    • 一、题目
    • 二、题解

一、题目

28. Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “sadbutsad”, needle = “sad”
Output: 0
Explanation: “sad” occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:

Input: haystack = “leetcode”, needle = “leeto”
Output: -1
Explanation: “leeto” did not occur in “leetcode”, so we return -1.

Constraints:

1 <= haystack.length, needle.length <= 104
haystack and needle consist of only lowercase English characters.

题目来源: leetcode

二、题解

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n1 = haystack.length();
        int n2 = needle.length();
        int i = 0;
        int res = n1;
        while(i < n1){
            int index = i;
            int j = 0;
            bool flag = true;
            for(;j < n2;j++){
                if(haystack[i++] != needle[j]){
                    flag = false;
                    break;
                }
            }
            i = index + 1;
            if(flag) res = min(index,res);
        }
        if(res == n1) return -1;
        else return res;
    }
};

http://www.kler.cn/news/106835.html

相关文章:

  • 【纯离线】Ubuntu离线安装ntp时间同步服务
  • 汇总区间(Java)
  • 宏电5G RedCap工业智能网关获首个中国移动5G物联网开放实验室5G及轻量化产品能力认证
  • 企业管理系统有哪些?
  • apisix之插件开发,包含java和lua两种方式
  • Framework -- 系统架构
  • 利用经典热门电视剧写爆款公众号爆文10万+阅读量
  • 华为云 CodeArts Snap 智能编程助手 PyCharm 插件安装与使用指南
  • 傅里叶在图像中的应用FFT算法---fft实战应用案例
  • jvm线上异常排查流程
  • 如何查找特定基因集合免疫基因集 炎症基因集
  • 蓝桥杯第 2 场算法双周赛 第2题 铺地板【算法赛】c++ 数学思维
  • pdf转jpg的方法【ps和工具方法】
  • mysql-linux归档版安装
  • SSH安全登录远程主机
  • 蓝桥杯每日一题2032.10.24
  • 基于Canal同步MySQL数据到Elasticsearch
  • 【前端性能】性能优化手段-高频面试题
  • OpenCV官方教程中文版 —— 直方图的计算,绘制与分析
  • R语言与作物模型(以DSSAT模型为例)融合应用
  • GPT做SQL查询引擎的自然语言
  • 接口返回响应,统一封装(ResponseBodyAdvice + Result)(SpringBoot)
  • 前端TypeScript学习-交叉类型与泛型
  • [已解决]安装的明明是pytorch-gpu,但是condalist却显示cpu版本,而且torch.cuda.is_available 也是flase
  • 贪心算法学习——最大数
  • Maven第三章:IDEA集成与常见问题
  • SpringCloud Alibaba【三】Gateway
  • MySQL数据库——视图的更新、视图作用以及案例
  • LuatOS-SOC接口文档(air780E)--libgnss - NMEA数据处理
  • 【洛谷 P3654】First Step (ファーストステップ) 题解(模拟+循环枚举)