数据结构与算法:字符串的调整与替换(javascript)

565 阅读1分钟
// 字符串的调整与替换

// 【题目】

// 给定一个字符类型的数组 chas[],chas 右半区全是空字符,左半区不含有空字符。现在想将左半区中所有的空格字符替换成"%20",假设 chas 右半区足够大,可以满足替换所需要的空间,请完成替换函数。

// 【举例】

// 如果把chas的左半区看作字符串,为"a b c",假设chas的右半区足够大。替换后,chas的左半区为"a%20b%20%20c"。

// 【要求】

// 替换函数的时间复杂度为O(N),额外空间复杂度为O(1)。

const a1 = ["a", "b", "c", " ", " ", " ", "d", " ", " ", "e"];
const replace = arr => {
  let count = 0;
  for (let i = 0; i < a1.length; i++) {
    if (a1[i] === " ") {
      count += 3;
    } else {
      count++;
    }
  }
  for (let i = a1.length - 1; i >= 0; i--) {
    if (a1[i] === " ") {
      a1[count - 1] = "0";
      count--;
      a1[count - 1] = "2";
      count--;
      a1[count - 1] = "%";
      count--;
    } else {
      a1[count - 1] = a1[i];
      count--;
    }
  }
};
replace(a1);
console.log(a1);

// 补充问题:给定一个字符类型的数组chas[],其中只含有数字字符和“*”字符。现在想把所有的“*”字符挪到chas的左边,数字字符挪到chas的右边。请完成调整函数。

// 【举例】

// 如果把chas看作字符串,为"12**345"。调整后chas为"**12345"。

// 【要求】

// 1.调整函数的时间复杂度为O(N),额外空间复杂度为O(1)。2.不得改变数字字符从左到右出现的顺序。
const a = ["1", "2", "3", "*", "4", "*", "5"];
const modify = arr => {
  let index1 = arr.length - 1;
  let index2 = arr.length - 1;
  while (true) {
    if (index2 >= 0) {
      if (arr[index2] !== "*") {
        arr[index1] = arr[index2];
        index2--;
        index1--;
      } else {
        index2--;
      }
    } else {
      arr[index1] = "*";
      index1--;
      if (index1 < 0) {
        break;
      }
    }
  }
};
modify(a);
console.log(a);