Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 1. for each char in s1 find the longest string in s2
- 2. compare it with previous string and replace if longer than the old String
- */
- // 'AGGTAB', 'GXTXAYB' = 'GTAB'
- function getTheLongestString(s1, s2, longestString = '', startingIndex = 0) {
- let tempLongestString = '';
- if(s1.length > 0) {
- [...s1].map((char) => {
- let s2Index = s2.indexOf(char, startingIndex);
- if(s2Index > -1) {
- startingIndex = s2Index + 1;
- tempLongestString += char;
- }
- });
- longestString = (tempLongestString.length > longestString.length) ? tempLongestString : longestString;
- return getTheLongestString(s1.substr(1), s2, longestString);
- } else return longestString;
- }
- console.log(getTheLongestString('ABAZDC', 'BACBAD'));
- console.log(getTheLongestString('AGGTAB', 'GXTXAYB'));
- console.log(getTheLongestString('aaaa', 'aa'));
- console.log(getTheLongestString('ABBA', 'ABCABA'));
- /*
- ABAZDC, BACBAD = ABAD
- AGGTAB, GXTXAYB = GTAB
- aaaa, aa = aa
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement