SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   1.  for each char in s1 find the longest string in s2
  3.   2.  compare it with previous string and replace if longer than the old String
  4. */
  5.  
  6. //  'AGGTAB', 'GXTXAYB' = 'GTAB'
  7.  
  8. function getTheLongestString(s1, s2, longestString = '', startingIndex = 0) {
  9.  
  10.   let tempLongestString = '';
  11.    
  12.   if(s1.length > 0) {
  13.  
  14.     [...s1].map((char) => {
  15.    
  16.       let s2Index = s2.indexOf(char, startingIndex);
  17.      
  18.       if(s2Index > -1) {
  19.         startingIndex = s2Index + 1;
  20.         tempLongestString += char;
  21.       }
  22.      
  23.     });
  24.    
  25.     longestString = (tempLongestString.length > longestString.length) ? tempLongestString : longestString;
  26.  
  27.     return getTheLongestString(s1.substr(1), s2, longestString);
  28.  
  29.    
  30.   } else return longestString;
  31.  
  32. }
  33.  
  34. console.log(getTheLongestString('ABAZDC', 'BACBAD'));
  35. console.log(getTheLongestString('AGGTAB', 'GXTXAYB'));
  36. console.log(getTheLongestString('aaaa', 'aa'));
  37. console.log(getTheLongestString('ABBA', 'ABCABA'));
  38.  
  39. /*
  40.   ABAZDC, BACBAD = ABAD
  41.   AGGTAB, GXTXAYB = GTAB
  42.   aaaa, aa = aa
  43. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top