codewars-js练习
2021/2/18
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>
以上为自己思路供大家参考,可能有更优的思路。