I have been trying FCC questions recently, just like upgrading to fight monsters, I have passed one level at a time, which is quite attractive to me. I took the time to do the Basic Algorithm Scritping part today. According to some tips, it is relatively simple. I think the methods of handling some questions are worth learning from. For example, sometimes you have to process a character in a project. If you can't think of some related methods, it's quite troublesome. So, record it here. If you encounter some characters or array processing in the future, you can search this article, hoping to get some prompts instead of translating the document.
If you see this blogger, if you have better and simpler code or good ideas, please leave a message to communicate (I always think that only by learning other people’s excellent code can you make faster progress and more flexible thinking). For beginners, try to do it yourself without looking at the code. (The following questions do not need to consider parameter types. Strictly speaking, a judgment should be made on the parameter types, eg:typeOf(arg) === number)
1.Reverse a String
Flip string
First convert the string into an array, then use the reverse method of the array to flip the array order, and finally convert the array into a string.
Your result must be a string
function reverseString(str) { str = str.split('').reverse().join(''); return str;}reverseString("hello");2.Check for Palindromes
If the given string is palindrome, return true, otherwise, false.
If a string ignores punctuation, case and spaces, and reads directly and reads oppositely, then this string is palindrome (palindrome).
Note that you need to remove the extra punctuation and spaces of the string, and then convert the string to lowercase to verify that the string is palindrome.
The value of function parameters can be "racecar", "RaceCar" and "race CAR".
function palindrome(str) { // Good luck! str=str.replace(/[/ |/~|/`|/!|/@|/#|/$|/%|/^|/&|/*|/(|/)|/-|/_|/+|/=|/|//|/|/[|/]|/{|/}|/;/:|/"|/'|/,|/<|/.|/?]/g,""); //Remove punctuation marks, this is my Baidu, and I am not very familiar with js rules str = str.replace(//s+/g); str = str.toLowerCase(); var arr = str.split(''); arr = arr.reverse(); var str1 = arr.join(""); if(str === str1){ return true;} return false;}palindrome("eye");/*palindrome("eye") should return true.palindrome("race car") should return true.palindrome("not a palindrome") should return false.palindrome("A man, a plan, a canal. Panama") should return true.palindrome("never odd or even") should return true.palindrome("nope") should return false.palindrome("almostomla") should return false.palindrome("My age is 0, 0 si ega ym.") should return true.palindrome("1 eye for of 1 eye.") should return false.palindrome("0_0 (: /-/ :) 0-0") should return true.*/3.Title Case a Sentence
Make sure that the first letter of each word in the string is capitalized and the rest is lowercase. (eg:titleCase("I'm a little tea pot") should return "I'm A Little Tea Pot". titleCase("sHoRt AnD sToUt") should return "Short And Stout".)
/*This question is very simple. The main thing is to understand that split() is to split a string into an array join() is to turn the array into a string toLowerCase() toUpperCase() case conversion. Note that it is only valid for letters, and other characters (eg:/,!@) are invalid*/function titleCase(str) { str = str.split(" ");//Segment the string into an array according to spaces for (var i = 0; i < str.length; i++) { str[i] = str[i].toLowerCase(); str[i] = str[i].substring(0, 1).toUpperCase() + str[i].substring(1); } return str.join(" ");//Connect the array into a string through spaces}titleCase("I'm a little tea pot");4.Confirm the Ending
Checks whether a string (str) ends with the specified string (target).
If yes, return true; if not, return false. For example: confirmEnding("Bastian", "n") should return true. confirmEnding("Connor", "n") should return false. confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.
function confirmEnding(str, target) { // "Never give up and good luck will find you." // -- Falcor return str.substr(str.length-target.length) == target ? true:false;}confirmEnding("Bastian", "n");confirmEnding("He has to give me a new name", "na");/*confirmEnding("Bastian", "n") should return true.confirmEnding("Connor", "n") should return false.confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.confirmEnding("He has to give me a new name", "name") should return true.confirmEnding("He has to give me a new name", "me") should return true.confirmEnding("He has to give me a new name", "na") should return false.confirmEnding("If you want to save our world, you must worry. We dont know how much longer we can withstand the nothing", "mountain") should return false.*/5.Repeat a string repeat a string
Say important things 3 times!
Repeat a specified string num times, and return an empty string if num is a negative number. For example:
repeat("*", 3) should return "***".
repeat("abc", 3) should return "abcabcabc".
repeat("abc", 4) should return "abcabcabcabc".
repeat("abc", 1) should return "abc".
repeat("*", 8) should return "*********".
repeat("abc", -2) should return "".
When you can't complete the challenge, remember to use the ultimate move 'Read-Search-Ask'.
Here are some resources that will help you:
•Global String Object
function repeat(str, num) { // repeat after me var newsstr = str; if(num >1){ for(var i = 1; i< num ; i ++){ str +=newstr; } return str; }else if(num == 1){ return str; }else{ return ""; } }repeat("abc", 3);repeat("*", 3);6.Chunky Monkey
Monkeys eat bananas but break them into several sections to eat them!
Divide an array arr into several array blocks according to the specified array size.
For example: chunk([1,2,3,4],2)=[[1,2],[3,4]];
chunk([1,2,3,4,5],2)=[[1,2],[3,4],[5]];
function chunk(arr, size) { // Break it up.var arr1 = []; for (var i = 0; i < arr.length; i = i + size) { var arr2 = arr; arr1.push(arr2.slice(i, i + size)); } return arr1;}chunk(["a", "b", "c", "d"], 2);7.Falsy Bouncer
True and fake Monkey King!
Delete all false values in the array.
In JavaScript, false values are false, null, 0, "", undefined, and NaN.
When you can't complete the challenge, remember to use the ultimate move 'Read-Search-Ask'.
Here are some resources that will help you:
•Boolean Objects
•Array.filter()
For example:
bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9].
bouncer(["a", "b", "c"]) should return ["a", "b", "c"].
bouncer([false, null, 0, NaN, undefined, ""]) should return [].
bouncer([1, null, NaN, 2, undefined]) should return [1, 2].
/* This question is about understanding filter. This is my initial code. It is not well written and has little reference value. You should also pay attention to NaN comparison. yourself is not equal to yourself (NaN != NaN )*/function bouncer(arr) { // Don't show a false ID to this bouncer. var arr1 =[]; var j = 0; arr.filter(function(val, index) { if (val === false || val === null || val === 0 || val === "" || val === undefined || val !== val) { arr1.push(index); } }); var len = arr1.length; for(var i = 0; i < len ; i++){ arr.splice(arr1[i]-j,1); j++; } return arr;}bouncer([7, "ate", "", false, 9]);8.Seek and Destroy
Jinx's Mortar!
Implement a destroyer function, the first parameter is the array to be destroyed, and the remaining parameters are the values to be destroyed.
For example:
destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
destroyer([2, 3, 2, 3], 2, 3) should return [].
destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].
Here are some resources that will help you:
•Arguments object
•Array.filter()
function destroyer(arr) { // Remove all the values var tempArguments = arguments; return arr.filter(function(entry) { for(var i = 1; i< tempArguments.length; i++) { if (entry == tempArguments[i]) { return false; } } return true; });}destroyer([1, 2, 3, 1, 2, 3], 2, 3);9. Where do I belong
Where am I?
First sort the array, then find the specified value at the location of the array, and finally return the index corresponding to the location.
For example: where([1,2,3,4], 1.5) should return 1. Because 1.5 is inserted into the array [1, 2, 3, 4] and becomes [1, 1.5, 2, 3, 4], and the index value corresponding to 1.5 is 1.
Similarly, where([20,3,5], 19) should return 2. Because the array will be sorted first as [3,5,20], 19 is inserted into the array [3,5,20] and becomes [3,5,19,20], and the index value corresponding to 19 is 2.
Here are some resources that will help you:
•Array.sort()
function where(arr, num) { // Find my place in this sorted array. //Note the sort() sort() sort rule arr.sort(function(a,b){ return a- b; }); for(var i =0;i<arr.length;i++){ if(arr[i]>num | arr[i] == num){ return i; } } return arr.length;}where([5, 3, 20, 3], 5);10.Caesars Cipher
Let God belong to God and Caesar belong to Caesar.
Next, we will introduce the Caesar password Caesar cipher, also known as shift password, which is popular all over the world.
The shift password means that the letters in the password will be shifted according to the specified number.
A common case is the ROT13 password, and the letters will be shifted by 13 positions. By 'A' ↔ 'N', 'B' ↔ 'O', and so on.
Write a ROT13 function to implement the input encrypted string and output the decrypted string.
All letters are capitalized, do not convert any non-letter characters (for example: spaces, punctuation marks). If you encounter these special characters, skip them.
For example:
rot13("SERR PBQR PNZC") should be decoded to "FREE CODE CAMP"
rot13("SERR CVMMN!") should be decoded as "FREE PIZZA!"
rot13("SERR YBIR?") should be decoded as "FREE LOVE?"
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.") should be decoded as "THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX."
Here are some resources that will help you:
•String.charCodeAt()
•String.fromCharCode()
function rot13(str) { // LBH QVQ VG! var arr = str.toUpperCase().split(" "); var str1 = []; for (var i = 0; i < arr.length; i++) { var arr1 = arr[i].split(""); for (var j = 0; j < arr1.length; j++) { var num = arr1[j].charCodeAt(); if (num >= 65 && num <= 90) { arr1[j] = num + 13 > 90 ? String.fromCharCode(64 + (num + 13 - 90)):String.fromCharCode(num + 13); //64 + (num + 13 - 90) To understand why it is 64, } } str1.push(arr1.join("")); } return str1.join(" ");}// Change the inputs below to testrot13("SERR PBQR PNZC");The above article briefly discusses some basic algorithm problems in character and array in js is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.