js----去掉字符串str中,連續重復的地方 的2種方法


在學習百度前端學院js課程的時候碰到這樣一個練習  “去掉字符串str中,連續重復的地方”,

我自己做法是:將字符串變為數組A,創建一個空數組B,對數組A進行循環,再在循環里面拿A的數組元素一個一個和B的最后一個數組元素比,不一致的元素放進數組B中

然后再將數組B用字符串的形式表現出來,自己的代碼如下:

 1 function removeRepetition(str) {
 2             var result = "",  //空的結果
 3                 strA =str.split(""), //將字符串進行分割,變成數組
 4                 strB = [],  //創建空的字符串
 5                 j=0;
 6             
 7               for(var i=0;i<strA.length;i++){   //對分割好,已變成數組的字符串A進行循環
 8                  if(strA[i] !=strB[j]){     //判斷循環到的A的元素和B的最后一位元素是否相等(因為B是一個空數組)
 9                     j++;              //j一定要先加1
10                     strB[j]=strA[i];
11                  }
12               }
13            result=(strB.toString()).replace(/,/g,"");
14             
15             return result;
16         }
17 
18 // 測試用例
19 
20 
21 console.log(removeRepetition("aaa")); // ->a
22 console.log(removeRepetition("abbba")); // ->aba
23 console.log(removeRepetition("aabbaabb")); // ->abab
24 console.log(removeRepetition("")); // ->
25 console.log(removeRepetition("abc")); // ->abc
26 console.log(removeRepetition("aaaaaaaaaaaabsssssssssssssscddddddddddddddddd")); // ->abc

然后網上找了下別人的寫法,寫的更好,代碼如下:

 1  function removeRepetition(str){
 2         var result="";
 3         len=str.length;    //一定要現將str的長度先取出來,因為在循環的時候每次切割字符串是會改變字符串長度的
 4         for(var i=0 ; i<len;i++){
 5             if(str[0]==str[1]){
 6                 str=str.slice(1);
 7             }else{
 8                 result=result+str[0];
 9                 str=str.slice(1);
10             }
11         }
12         return result;
13     }
18 // 測試用例
19 
20 
21 console.log(removeRepetition("aaa")); // ->a
22 console.log(removeRepetition("abbba")); // ->aba
23 console.log(removeRepetition("aabbaabb")); // ->abab
24 console.log(removeRepetition("")); // ->
25 console.log(removeRepetition("abc")); // ->abc
26 console.log(removeRepetition("aaaaaaaaaaaabsssssssssssssscddddddddddddddddd")); // ->abc


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM