简体   繁体   English

如何使用数字反转字符串,但不要反转1和0?

[英]How to Reverse a string with numbers, but don't reverse 1 and 0?

I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string eg, 2345678910 would be 1098765432. 我正在学习随机算法,我目前在一个库存中,我必须反转包含数字的字符串,但我不会在字符串中反转1和0,例如,2345678910将是1098765432。

Here's what I've done so far: 这是我到目前为止所做的:

 function split(str) { let temp = []; temp = str.split(''); const backwards = []; const totalItems = str.length - 1; for (let i = totalItems; i >= 0; i--) { backwards.push(temp[i]); } return backwards.join('').toString(); } console.log(split("10 2 3 USA")); console.log(split("2345678910")); 

I am currently having the issue of not reversing the 10. 我目前的问题是没有扭转10。

What am I doing wrong? 我究竟做错了什么?

You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10 . 您可以使用文本中不存在的指定字符替换10 ,并在运行实现的算法后将其替换为10

 let out_of_alphabet_character = '#'; var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g"); function specific_revert(str) { str = str.replace(/(10)/g, out_of_alphabet_character); let temp = []; temp = str.split(''); const backwards = []; const totalItems = str.length - 1; for (let i = totalItems; i >= 0; i--) { backwards.push(temp[i]); } return backwards.join('').toString().replace(reg_for_the_alphabet, '10'); } console.log(specific_revert("10 2 3 USA")); console.log(specific_revert("234567891010")); 

You can reduce over the matched array from using a regular expression. 您可以使用正则表达式reduce匹配的数组。 It's more costly than a for/loop that concatenates strings, but it was fun figuring it out. 它比连接字符串的for / loop更昂贵,但它很有趣。

 function split(str) { const re = /([A-Z23456789 ]+)|(10)/g return str.match(re).reduce((acc, c) => { // if the match is 10 prepend it to the accumulator // otherwise reverse the match and then prepend it acc.unshift(c === '10' ? c : [...c].reverse().join('')); return acc; }, []).join(''); } console.log(split('2345678910')); console.log(split('10 2 3 US A')); console.log(split('2 3 US A10')); 

Just check for the special case & code the normal logic or reversing as usual 只需检查特殊情况并编码正常逻辑或正常反转

  const reverse = str => { let rev = ""; for (let i = 0; i < str.length; i++) { if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') { rev = '10' + rev; i++; } else rev = str[i] + rev; } return rev; } console.log(reverse("10 2 3 USA")); // returns ASU 3 2 10 console.log(reverse("2345678910")); // returns 1098765432 

You need some pre-conditions to check each character's value. 您需要一些前置条件来检查每个角色的值。

Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters AZ (including 0 and 1) are simply characters. 由于问题的模糊性,有理由相信OP定义的数字系统包括[2,3,4,5,6,7,8,9,10]和所有其他字符AZ(包括0和1)只是字符。

 String.prototype.isNumeric = function() { return !isNaN(parseFloat(this)) && isFinite(this); }; function reverse(str) { let tokens = [], len = str.length; while (len--) { let char = str.charAt(len); if (char.isNumeric()) { if (len > 0 && str.charAt(len - 1).isNumeric()) { let curr = parseInt(char, 10), next = parseInt(str.charAt(len - 1), 10); if (curr === 0 && next === 1) { tokens.push(10); len--; continue; } } } tokens.push(char); } return tokens.join(''); } console.log(reverse("10 2 3 USA")); console.log(reverse('2345678910')); 

Output: 输出:

 ASU 3 2 10 1098765432 

Below is a recursive approach. 下面是一个递归方法。

 function f(s, i=0){ if (i == s.length) return ''; if (['0', '1'].includes(s[i])){ let curr = s[i]; while (['0', '1'].includes(s[++i])) curr += s[i] return f(s, i) + curr; } return f(s, i + 1) + s[i]; } console.log(f('10 2 3 US A')); console.log(f('2345678910')); console.log(f('USA101001')); 

Nice question so far. 到目前为止好的问题。

You may try this recursive approach(if not changing 10 for other character not allowed): 您可以尝试这种递归方法(如果不更改10不允许其他字符):

 function reverseKeepTen(str, arr = []) { const tenIdx = str.indexOf('10'); if (!str.length) { return arr.join(''); } if (tenIdx === -1) { return [...str.split('').reverse(), ...arr].join(''); } else { const digitsBefore = str.slice(0, tenIdx); const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10]; return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr]) } }; console.log(reverseKeepTen('101234105678910')) // 109876510432110 console.log(reverseKeepTen('12341056789')) // 98765104321 console.log(reverseKeepTen('1012345')) // 5432110 console.log(reverseKeepTen('5678910')) // 1098765 console.log(reverseKeepTen('10111101')) // 11011110 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM