Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. // LCS Solution 1
  2. function longestCommonSubsequence(xString, yString) {
  3.  
  4. function recur(xArray, yArray, lcs) {
  5. var xElement = xArray[0];
  6. var yElement = yArray[0];
  7. // Base case --> out of string!
  8. // return the LCS of this section
  9. if (!xElement || !yElement) {
  10. return lcs;
  11. }
  12. // First Property
  13. if (xElement === yElement) {
  14. // append element to Subseq
  15. // remove element from each array
  16. // find LCS of remaining section
  17. return recur(xArray.slice(1), yArray.slice(1), lcs += xElement);
  18. }
  19.  
  20. // Second Property
  21. if (xElement !== yElement) {
  22. // return the larger of the following cases:
  23. // Case 1, the LCS does not end in xElement
  24. var case1 = recur(xArray.slice(1), yArray, lcs);
  25. // Case 2, the LCS does not end in yElement
  26. var case2 = recur(xArray, yArray.slice(1), lcs);
  27. return case1.length > case2.length ? case1 : case2;
  28. }
  29. }
  30.  
  31. return recur(xString, yString, '');
  32. }
  33.  
  34. // LCS Solution #2
  35. function longestCommonSubsequence2(xString, yString) {
  36. // Base case --> empty string
  37. if (xString === '' || yString === '') {
  38. return '';
  39. }
  40.  
  41. // grab the first element
  42. var xElement = xString.charAt(0);
  43. var yElement = yString.charAt(0);
  44.  
  45. // First Property: elements match
  46. if (xElement === yElement) {
  47. // return element + the LCS of remaining sections
  48. return xElement + longestCommonSubsequence2(xString.slice(1), yString.slice(1));
  49. }
  50.  
  51. // Second Property: elements do not match
  52. // return the longer of the following cases:
  53. // Case 1, the LCS does not begin in xElement
  54. var case1 = longestCommonSubsequence2(xString.slice(1), yString);
  55. // Case 2, the LCS does not end in yElement
  56. var case2 = longestCommonSubsequence2(xString, yString.slice(1));
  57. return case1.length > case2.length ? case1 : case2;
  58. }
  59.  
  60. console.log("1a", longestCommonSubsequence("a", "b")); // ""
  61. console.log("2a", longestCommonSubsequence2("a", "b")); // ""
  62. console.log("1c", longestCommonSubsequence("BANANA", "ATANA")); // "AANA"
  63. console.log("2c", longestCommonSubsequence2("BANANA", "ATANA")); // "AANA"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement