1. 程式人生 > >js----去掉字符串str中,連續重復的地方 的2中方法

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

string mov 人的 改變 連續 bsp aabb length ret

在學習百度前端學院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


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