Home > Software design >  Reverse a string using two-pointer method in JS
Reverse a string using two-pointer method in JS

Time:08-22

I am trying to reverse a string. I am aware of .reverse function and other methods in Js to do so, but i wanted to do it this two-pointer method.

The problem is the string is not getting updated. Is there anything i am not aware of strings. Whats wrong here ?

function reverseString(s) {
  let lengthOfStr = 0;

  if ((s.length - 1) % 2 == 0) {
    lengthOfStr = (s.length - 1) / 2
  } else {
    lengthOfStr = ((s.length - 1) / 2)   1;
  }
  let strLengthLast = s.length - 1;
  for (let i = 0; i <= lengthOfStr; i  ) {
    let pt1 = s[i];
    let pt2 = s[strLengthLast];

    s[i] = pt2;
    s[strLengthLast] = pt1;
    console.log('----', s[i], s[strLengthLast]);
    strLengthLast--;
  }
  return s;
}
console.log(reverseString('hello'));

CodePudding user response:

Unlike in C, strings in JavaScript are immutable, so you can't update them by indexing into them. Example:

let s = 'abc';
s[1] = 'd';
console.log(s); // prints abc, not adc

You'd need to do something more long-winded in place of s[i] = pt2;, like s = s.substring(0, i) pt2 s.substring(i 1);, and similarly for s[strLengthLast] = pt1; (or combine them into one expression with 3 calls to substring).

CodePudding user response:

I'm not sure why it doesnt update the string, but if you handle the replacement as an array/list it works as follows:

function reverseString(s) {
  let lengthOfStr = 0;
  sSplit = s.split("");

  if ((s.length - 1) % 2 === 0) {
    lengthOfStr = (s.length - 1) / 2
  }
  else {
    lengthOfStr = ((s.length - 1) / 2)   1;
  }
  let strLengthLast = s.length - 1;
  for (let i = 0; i <= lengthOfStr; i  ) {
    let pt1 = sSplit[i];
    let pt2 = sSplit[strLengthLast];

    sSplit[i] = pt2;
    sSplit[strLengthLast] = pt1;
    console.log('----', sSplit[i], sSplit[strLengthLast],sSplit);
    strLengthLast--;
  }
  return sSplit.join("");
}
console.log(reverseString('Hello'));

returns: Hello => olleH

  • Related