diff --git a/logic-exercises/exercise-day-4/longestCommon.js b/logic-exercises/exercise-day-4/longestCommon.js new file mode 100644 index 0000000..dff6041 --- /dev/null +++ b/logic-exercises/exercise-day-4/longestCommon.js @@ -0,0 +1,20 @@ +function longestCommon(strs) { + if (strs.length === 0) + return ""; + var commonPrefix = ""; + for (var i = 0; i < strs[0].length; i++) { + var currentChar = strs[0][i]; + var areAllCharsSame = true; + for (var j = 0; j < strs.length; j++) { + if (strs[j][i] !== currentChar) { + return commonPrefix; + } + } + if (currentChar) { + commonPrefix += currentChar; + } + } + return commonPrefix; +} +console.log(longestCommon(["Palmeiras", "Palermo"])); +console.log(longestCommon(["porco", "gamba"])); diff --git a/logic-exercises/exercise-day-4/longestCommon.test.ts b/logic-exercises/exercise-day-4/longestCommon.test.ts new file mode 100644 index 0000000..e69de29 diff --git a/logic-exercises/exercise-day-4/longestCommon.ts b/logic-exercises/exercise-day-4/longestCommon.ts new file mode 100644 index 0000000..2db8ec8 --- /dev/null +++ b/logic-exercises/exercise-day-4/longestCommon.ts @@ -0,0 +1,24 @@ +function longestCommon(strs) { + + if (strs.length === 0) return "" + + let commonPrefix = "" + for (let i = 0; i < strs[0].length; i++) { + let currentChar = strs[0][i] + let areAllCharsSame = true + + for (let j = 0; j < strs.length; j++) { + if(strs[j][i] !== currentChar) { + return commonPrefix + } + } + + if(currentChar) { + commonPrefix += currentChar + } + } + return commonPrefix +} + +console.log(longestCommon(["Palmeiras", "Palermo"])) +console.log(longestCommon(["porco", "gamba"])) \ No newline at end of file diff --git a/logic-exercises/exercise-day-4/package.json b/logic-exercises/exercise-day-4/package.json new file mode 100644 index 0000000..c1aaf1a --- /dev/null +++ b/logic-exercises/exercise-day-4/package.json @@ -0,0 +1,13 @@ +{ + "name": "exercise-day-4", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start":"clear && tsc --outFile longestCommon.js longestCommon.ts && node longestCommon.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC" +}