Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report