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


 

posted @ 2018-07-18 09:32  总是学不会啊  阅读(3968)  评论(0编辑  收藏  举报