Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement the strStr () function in C++

Shulou Source: shulou.com Published: 2022-05-31 13:52:43 09月17日 Update

This article editor for you a detailed introduction of "C++ how to achieve strStr () function", the content is detailed, the steps are clear, the details are handled properly, I hope this "C++ how to achieve strStr () function" article can help you solve your doubts, the following follow the editor's ideas slowly in depth, together to learn new knowledge.

Implement strStr () implements the strStr () function

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C "s strstr () and Java" s indexOf ().

This problem allows us to find the location of the first occurrence of another string in one string. First, we have to make some judgments. If the substring is empty, it returns 0, and if the substring length is greater than the parent string length, it returns-1. Then start traversing the parent string, which does not need to traverse the entire parent string, but traverses to a position where the rest of the length is equal to the substring, which improves the efficiency of the operation. Then, for each character, traverse the substring, and compare one character to another. If the corresponding position is different, you will jump out of the loop. If you have not jumped out of the loop all the time, you can indicate that the substring appears and return the starting position. The code is as follows:

Class Solution {public: int strStr (string haystack, string needle) {if (needle.empty ()) return 0; int m = haystack.size (), n = needle.size (); if (m < n) return-1; for (int I = 0; I

Tags: Characters strings functions positions lengths loops clips articles codes contents fruits appropriateness brevity two beginnings ideas efficiency new knowledge Akiko more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Linux MySQL Shulou Technology