您好,欢迎来到百家汽车网。
搜索
您的当前位置:首页LeetCode数组/字符串 28. 找出字符串中第一个匹配项的下标

LeetCode数组/字符串 28. 找出字符串中第一个匹配项的下标

来源:百家汽车网

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回  -1 

示例 1:

输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。

示例 2:

输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。

AC很常规的字符串

class Solution {
public:
    int strStr(string haystack, string needle) {
        int length1=haystack.size();
        int length2=needle.size();
        bool pipei=false;
        for(int i=0;i<length1;i++){
            if(haystack[i]==needle[0]){
                if(hedui(haystack,needle,i,length2)) return i;
            }
        }
        return -1;
    }
    bool hedui(string haystack, string needle,int xiabiao,int length2){
        for(int i=0;i<length2;i++){
            if(haystack[xiabiao]!=needle[i]) return false;
            xiabiao++;
        }
        return true;

    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baijiahaobaidu.com 版权所有 湘ICP备2023023988号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务