codewars练习(javascript)-2021/2/18

codewars-js练习

2021/2/18

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<7kyu>【Switcheroo】

Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.

切换字母a和b的位置

example

'acb'// 'bca'
'aabacbaa' // 'bbabcabb'
'ccccc'// 'ccccc'

solution

<script type="text/javascript">
    function switcheroo(x){
      // console.log(x);
      // 正则表达式检测传进的字符串中是否具有a或b
      var t = /[a|b]/.test(x);
      if(t){
        var arr = x.split('');
        // 将a和b进行替换
        for(var i=0;i<arr.length;i++){
          if(arr[i]=='a')arr[i]='b';
          else if(arr[i] =='b')arr[i] = 'a';
          // console.log('arr',arr);
        }
        return arr.join('');
      }else{
        return x;
      }
    }
 		
		// 验证
		console.log(switcheroo('abc'));// 'bac'
    console.log(switcheroo('aaabcccbaaa'));// 'bbbacccabbb'
    console.log(switcheroo('ccccc'));// 'ccccc'
    console.log(switcheroo('ab'));//ba
	</script>
【2】<7kyu>【Double Trouble】

Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.

给定一个由整数(x)和目标(t)组成的数组,你必须找出数组中任意两个连续的数字是否和为t。如果是,删除第二个数字。

example

x = [1, 2, 3, 4, 5]
t = 3

1+2 = t, so remove 2. No other pairs = t, so rest of array remains:

[1, 3, 4, 5]

solution

<script type="text/javascript">
    function trouble(x, t){
      // console.log(x,t)
      for(var i=0;i<x.length;i++){
        for(var j=i+1;j<i+2;j++){
          if(x[i] + x[j] == t){
            x.splice(j,1);
            // console.log(x)
            j--;
          }
        }
        
      }
      return x;
    }
 		
		// 验证
		console.log(trouble([1, 3, 5, 6, 7, 4, 3],7));//[1, 3, 5, 6, 7, 4]
    console.log(trouble([4, 1, 1, 1, 4],2));// [4, 1, 4]
    console.log(trouble([2, 2, 2, 2, 2, 2], 4));//[2]
	</script>

以上为自己思路供大家参考,可能有更优的思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值