Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// How do you find the length of the longest substring without repeating
//characters?
const longestSubstring = str => {
if (typeof str !== "string" || !str.length) {
return null;
}
const letters = str
.toLowerCase()
.replace(/[\W_]/g, "")
.split("");
let results = [];
let maxLength = 0;
for (let i = 0; i < letters.length; i++) {
if (results.indexOf(letters[i]) === -1) {
results.push(letters[i]);
} else {
i = i - 1;
results = [];
}
if (maxLength < results.length) {
maxLength = results.length;
}
}
return maxLength;
};
//Time-complexity: O(n)
//Test cases
const caseTest = [
{ input: "", output: null },
{ input: 123, output: null },
{ input: "abBcB", output: 4 },
{ input: "abcdefgh", output: 8 },
{ input: "abccdeggh", output: 4 },
{ input: "abcddghabcdf", output: 6 },
{ input: "abcCdEggh", output: 4 },
{ input: "abccde ggh", output: 4 },
{ input: "abc@cde_ggh", output: 4 },
{ input: "Sh/i. lp@IA", output: 5 }
];
caseTest.forEach(({ input, output }, index) => {
console.log(
`caseTest: ${index} (${input}) (${
longestSubstring(input) === output ? "success" : "failure"
})`
);
});
@ShilpiMaurya

This comment has been minimized.

Copy link
Owner Author

@ShilpiMaurya ShilpiMaurya commented Nov 23, 2020

This program is already considering upper case alphabets and lower case alphabets different, it is evident in third test case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment