The longest substring

C++: Finding the Longest Substring

To find the longest substring in C++, you can use the following approach:

  1. Initialize Variables: Create variables to store the starting index of the current substring, the length of the longest substring found so far, and the starting index of the longest substring.

  2. Iterate Through the String: Use a loop to iterate through the input string. Within the loop, keep track of the characters encountered and their positions.

  3. Update Substring Information: As you iterate through the string, update the current substring's starting index and length if a longer substring is found.

  4. Return Longest Substring: Once the loop has finished, return the longest substring found based on the stored information.

Here's a sample C++ code snippet that demonstrates this approach:

#include <string>
#include <iostream>

std::string findLongestSubstring(const std::string& input) {
    int start = 0;
    int maxLength = 0;
    int longestStart = 0;

    for (int i = 0; i < input.length(); ++i) {
        if (input[i] != input[i - 1]) {
            if (i - start > maxLength) {
                maxLength = i - start;
                longestStart = start;
            }
            start = i;
        }
    }

    return input.substr(longestStart, maxLength);
}

int main() {
    std::string input = "abccccdefg";
    std::string longestSubstring = findLongestSubstring(input);
    std::cout << "Longest substring: " << longestSubstring << std::endl;
    return 0;
}

In this code, the findLongestSubstring function takes an input string and iterates through it to find the longest substring without repeating characters. The main function demonstrates its usage by finding the longest substring in the input string "abccccdefg" and printing the result.