This JavaScript program finds the longest substring without repeating characters from a given string. It efficiently tracks character occurrences to build substrings and identifies the longest one among them.
- Iterates through a string to create substrings.
- Uses an array to store substrings that contain unique characters.
- Utilizes the
reducemethod to determine the longest substring.
-
Initialization:
- A string
strArraycontains the input characters. - An array
outputis created to store substrings without repeating characters. - A variable
noRepeatingResultis initialized to accumulate the current substring being processed.
- A string
-
Iterating Through the String:
- The program loops through each character in
strArray. - For each character, it checks if it already exists in
noRepeatingResult.- If it does, the current substring is pushed to the
outputarray, andnoRepeatingResultis reset to start a new substring with the current character. - If it does not exist, the character is added to
noRepeatingResult.
- If it does, the current substring is pushed to the
- The program loops through each character in
-
Final Output:
- After the loop, the last accumulated substring is pushed to the
outputarray. - The program then uses the
reducemethod to find the longest substring by comparing the lengths of the substrings inoutput.
- After the loop, the last accumulated substring is pushed to the
-
Displaying Results:
- The program prints the array of substrings and the longest substring found.
Given the input string:
var strArray = "abcdefghbijklmnopaqrstuvwxyzcd";
## Result is
--------String Array is----------------
[abcdefgh, bijklmnopaqrstuvwxyzcd]
--------Resulted SubString is----------------
longest substring is : bijklmnopaqrstuvwxyzcd