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

    strstr()函数返回匹配的首字符索引。

    可以使用常规的匹配算法,蛮力算法

    遍历haystack到m-n+1的同时遍历needle从0到n,while来判断两个string对应字符是否相等。

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int m = haystack.size(), n = needle.size();
            if (n == 0)
                return 0;
            for (int i = 0; i < m - n + 1; i++) {
                int j = 0;
                while (haystack[i + j] == needle[j]) {
                    j++;
                    if (j == n)
                        return i;
                }
                j++;
            }
            return -1;
        }
    };
    // 6 ms
  • 相关阅读:
    lr http_get访问webservice
    lr http_post请求webservice
    快速幂(fast power)
    运算符重载
    1010 Radix 二分
    1054 The Dominant Color
    1042 Shuffling Machine
    1059 Prime Factors
    1061 Dating
    1078 Hashing
  • 原文地址:https://www.cnblogs.com/immjc/p/8044847.html
Copyright © 2011-2022 走看看