Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is the code from yesterday. It was not working on the example
- // "12345" because we reached the end of the string, which meant we
- // will not enter again in the for loop, and in that case, the if statement
- // is not being called (because all the elements in the string are unique).
- // To fix this, I added the if statement also after the loop.
- function longestSubseq(str) {
- var map = new Map();
- var maxLength = 0;
- var currentLength = 0;
- for (var i = 0; i < str.length; i++) {
- if (map.has(str[i])) {
- if (currentLength > maxLength) {
- maxLength = currentLength;
- }
- map = new Map();
- currentLength = 0;
- } else {
- currentLength++;
- map.set(str[i], 1);
- }
- }
- // in case we reach the end of the string and the current Length of the
- // last substring of nonrepeting characters is > maxLength, we return
- // the currentLength
- if (currentLength > maxLength) {
- return currentLength;
- }
- return maxLength;
- }
- // Nevertheless, not all the cases are being covered by my function
- // For example, longestSubseq("abcbdf") will return 3 instead of 4
- function correctLongestSubseq(str) {
- // I use this map in order to store the last occurence of each character
- var chrVisited = new Map();
- var maxLength = 0;
- var indexStart = 0;
- for (var i = 0; i < str.length; i++) {
- // if we already have the character and the indexStart is not ahead of the
- // last index of str[i], indexStart will be switched to the prev position of str[i]
- if (chrVisited.has(str[i]) && indexStart < chrVisited.get(str[i]) + 1) {
- indexStart = chrVisited.get(str[i]) +1;
- }
- // we remember the maximum length so far by comparing maxLength with the lenght of
- // current substring of nonRepeting characters
- if (maxLength < i - indexStart + 1) {
- maxLength = i - indexStart+1;
- }
- // we update the map with the latest position of str[i]
- chrVisited.set(str[i], i);
- }
- return maxLength;
- }
- //this is the input from yesterday which now returns true
- console.assert(true, longestSubseq("12345"), 5);
- // they all return true
- console.assert(true, correctLongestSubseq("abcbdgf"), 5);
- console.assert(true, correctLongestSubseq("abadla"), 4);
- console.assert(true, correctLongestSubseq("1234567"), 7);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement