In the study of Baidu front-end College JS course encountered such a practice "remove string str, the place of continuous repetition",
My own practice is to change the string to array a, create an empty array B, loop through group A, and then take an array element of a in the loop with the last array element of A and B, and the inconsistent elements into array b
Then the array B is shown in the form of a string, and its code is as follows:
1 functionremoverepetition (str) {2 varresult = "",//NULL results3Stra =str.split (""),//to split the string into an array4StrB =[],//Create an empty string5J=0;6 7 for(vari=0;i<stra.length;i++) {//pair The string A that has been transformed into an array is looped .8 if(Stra[i]! =Strb[j]) {//Determine if the elements of a loop to and the last element of B are equal (because B is an empty array)9J + +; J must add 1 first .Tenstrb[j]=Stra[i]; One } A } -result= (Strb.tostring ()). Replace (/,/g, ""); - the returnresult; - } - - //Test Cases + - +Console.log (Removerepetition ("AAA"));//->a AConsole.log (Removerepetition ("Abbba"));//->aba atConsole.log (Removerepetition ("Aabbaabb"));//->abab -Console.log (Removerepetition (""));// - -Console.log (Removerepetition ("abc"));//->ABC -Console.log (Removerepetition ("aaaaaaaaaaaabsssssssssssssscddddddddddddddddd"));//->ABC
Then on the internet to find someone else's writing, write better, the code is as follows:
1 function removerepetition (str) { 2 var result= ""; 3 Len=str.length; // Be sure to take the length of STR first, because each time the string is cut in the loop, it will change the length of the string.
4 for(vari=0; i<len;i++){5 if(str[0]==str[1]){6Str=str.slice (1);7}Else{8Result=result+str[0];9Str=str.slice (1);Ten } One } A returnresult; -}
18//test Case Console.log (removerepetition ("AAA")); ->a22 Console.log (removerepetition ("Abbba")); ->aba23 Console.log (removerepetition ("Aabbaabb")); ->abab24 Console.log (Removerepetition ("")); ->25 Console.log (Removerepetition ("abc")); ->abc26 Console.log (removerepetition ("aaaaaaaaaaaabsssssssssssssscddddddddddddddddd")); ->abc
JS----Remove the string in str, the 2-way method of continuous repetition