最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Given a string S, return the "reversed" string where all chars that are not a letter stay in the

programmeradmin3浏览0评论

I've spent a while on this problem and would prefer to make this work without having to redo the problem with a different method. I understand it's not returning the '!' because of the length of the index I set it to but I'm honestly stump on how I can edge case this or something.

var reverseOnlyLetters = function(S) {
    let result = [];
    const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let sArr = S.split('')
    for (let i = 0; i < sArr.length; i++) {
        if (sArr[i].match(/[A-Z]/gi)) {
            result.push(sArr[i])
        }
    }
    result = result.reverse()
    let other = S.split('');
    console.log(result); //[ 'd', 'c', 'b', 'a' ]
    console.log(other) //[ 'a', 'b', '-', 'c', 'd' ]
    for (j = 0; j < other.length; j++) {
        if (!letters.includes(other[j]) && letters.includes(result[j])) {
            result.splice(j,0,other[j])
        }
    }
return result.join('');
};

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q!")) //"Qedo1ct-eeLg=ntse-T!"

I've spent a while on this problem and would prefer to make this work without having to redo the problem with a different method. I understand it's not returning the '!' because of the length of the index I set it to but I'm honestly stump on how I can edge case this or something.

var reverseOnlyLetters = function(S) {
    let result = [];
    const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let sArr = S.split('')
    for (let i = 0; i < sArr.length; i++) {
        if (sArr[i].match(/[A-Z]/gi)) {
            result.push(sArr[i])
        }
    }
    result = result.reverse()
    let other = S.split('');
    console.log(result); //[ 'd', 'c', 'b', 'a' ]
    console.log(other) //[ 'a', 'b', '-', 'c', 'd' ]
    for (j = 0; j < other.length; j++) {
        if (!letters.includes(other[j]) && letters.includes(result[j])) {
            result.splice(j,0,other[j])
        }
    }
return result.join('');
};

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q!")) //"Qedo1ct-eeLg=ntse-T!"
Share Improve this question asked Apr 15, 2021 at 3:57 Ron RanceRon Rance 1031 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

In the final loop, you're iterating over the original input string and you want to insert the symbol values into the reversed result string, posed of letters:

for (j = 0; j < other.length; j++) {
    if (!letters.includes(other[j]) && letters.includes(result[j])) {
        // problem above:              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
        result.splice(j,0,other[j])
    }
}

But when you want to do this, the letters won't include result[j] - just remove that, and your code will work. You don't care about what (reversed characters) result contains at that point, you want to replace the value at other index being iterated over regardless.

var reverseOnlyLetters = function(S) {
  let result = [];
  const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let sArr = S.split('')
  for (let i = 0; i < sArr.length; i++) {
    if (sArr[i].match(/[A-Z]/gi)) {
      result.push(sArr[i])
    }
  }
  result = result.reverse()
  let other = S.split('');
  // console.log(result); //[ 'd', 'c', 'b', 'a' ]
  // console.log(other) //[ 'a', 'b', '-', 'c', 'd' ]
  for (j = 0; j < other.length; j++) {
    if (!letters.includes(other[j])) {
      result.splice(j, 0, other[j])
    }
  }
  return result.join('');
};

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q!")) //"Qedo1ct-eeLg=ntse-T!"

I think a clearer way to approach this would be to first get an array of all letter characters (like you're doing), then just use a regular expression to match letters in the original string and replace them with .popped values from the array:

var reverseOnlyLetters = function(s) {
  const letters = s.match(/[a-z]/gi) || [];
  return s.replace(/[a-z]/gi, () => letters.pop());
};

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q!")) //"Qedo1ct-eeLg=ntse-T!"

Even if an answer is already given, here an easy solution without regex:

let str = 'Test1ng-Leet=code-Q!';

const isLetter = (c) => c.toLowerCase() !== c.toUpperCase();
// extract letter character
let letters = [...str].filter(c => isLetter(c));
// recreate a reversed string
let reversed = [...str].map((c) => isLetter(c) ? letters.pop() : c).join('');

console.log(str);
console.log(reversed);

Without using regex:

  • Identify letters: Use a predefined string containing all uppercase and lowercase letters.
  • Extract and reverse the letters: Loop through the string to extract letters, reverse the array of letters.
  • Reconstruct the string: Iterate over the original string and replace the letters with the reversed ones, while leaving non-letter characters in their original positions.

function reverseOnlyLetters(S) {
    const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    let letterArray = [];
    for (let char of S) {
        if (letters.includes(char)) {
            letterArray.push(char);
        }
    }
    
    letterArray.reverse();
    
    let letterIndex = 0;
    
    let result = '';
    for (let char of S) {
        if (letters.includes(char)) {
            result += letterArray[letterIndex++];
        } else {
            result += char;
        }
    }
    
    return result;
}

console.log(reverseOnlyLetters("Test1ng-Leet=code-Q")); // "Qedo1ct-eeLg=ntse-T!"

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论