Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active November 23, 2020 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShilpiMaurya/112e8ed87c995f99cec877cb94769c8a to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/112e8ed87c995f99cec877cb94769c8a to your computer and use it in GitHub Desktop.
// 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
Copy link
Author

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