Last active
November 23, 2020 14:09
-
-
Save ShilpiMaurya/112e8ed87c995f99cec877cb94769c8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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" | |
})` | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This program is already considering upper case alphabets and lower case alphabets different, it is evident in third test case.