Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. // This is the code from yesterday. It was not working on the example
  2. // "12345" because we reached the end of the string, which meant we
  3. // will not enter again in the for loop, and in that case, the if statement
  4. // is not being called (because all the elements in the string are unique).
  5. // To fix this, I added the if statement also after the loop.
  6. function longestSubseq(str) {
  7. var map = new Map();
  8. var maxLength = 0;
  9. var currentLength = 0;
  10. for (var i = 0; i < str.length; i++) {
  11. if (map.has(str[i])) {
  12. if (currentLength > maxLength) {
  13. maxLength = currentLength;
  14. }
  15. map = new Map();
  16. currentLength = 0;
  17. } else {
  18. currentLength++;
  19. map.set(str[i], 1);
  20. }
  21. }
  22. // in case we reach the end of the string and the current Length of the
  23. // last substring of nonrepeting characters is > maxLength, we return
  24. // the currentLength
  25. if (currentLength > maxLength) {
  26. return currentLength;
  27. }
  28. return maxLength;
  29. }
  30.  
  31. // Nevertheless, not all the cases are being covered by my function
  32. // For example, longestSubseq("abcbdf") will return 3 instead of 4
  33. function correctLongestSubseq(str) {
  34. // I use this map in order to store the last occurence of each character
  35. var chrVisited = new Map();
  36. var maxLength = 0;
  37. var indexStart = 0;
  38. for (var i = 0; i < str.length; i++) {
  39. // if we already have the character and the indexStart is not ahead of the
  40. // last index of str[i], indexStart will be switched to the prev position of str[i]
  41. if (chrVisited.has(str[i]) && indexStart < chrVisited.get(str[i]) + 1) {
  42. indexStart = chrVisited.get(str[i]) +1;
  43. }
  44. // we remember the maximum length so far by comparing maxLength with the lenght of
  45. // current substring of nonRepeting characters
  46. if (maxLength < i - indexStart + 1) {
  47. maxLength = i - indexStart+1;
  48. }
  49. // we update the map with the latest position of str[i]
  50. chrVisited.set(str[i], i);
  51.  
  52. }
  53. return maxLength;
  54. }
  55.  
  56. //this is the input from yesterday which now returns true
  57. console.assert(true, longestSubseq("12345"), 5);
  58.  
  59. // they all return true
  60. console.assert(true, correctLongestSubseq("abcbdgf"), 5);
  61. console.assert(true, correctLongestSubseq("abadla"), 4);
  62. console.assert(true, correctLongestSubseq("1234567"), 7);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement