回文字符串

154 阅读1分钟

回文字符串

思路

利用双端队列,每次从队头队尾取一个元素比较,如果有不同就返回false。

实现

class Deque {
  constructor() {
    this.count = 0;
    this.lowestCount = 0;
    this.items = {};
  }
  // 添加元素到双端队列队头
  addFront(element) {
    // 有三种情况
    /* 
    head=lowestCount
    0:a
    1:b
    2:c
    tail=count
    */
    if (this.isEmpty()) {
      this.addBack();
    } else if (this.lowestCount > 0) {
      this.lowestCount--;
      this.items[this.lowestCount] = element;
    } else {
      // 向后移动元素
      for (let i = this.count; i > this.lowestCount; i--) {
        this.items[i] = this.items[i - 1];
      }
      this.lowestCount = 0;
      this.items[this.lowestCount] = element;
      this.count++;
    }
  }
  addBack(element) {
    // 这样写有问题吗?
    this.items[this.count] = element;
    this.count++;
  }

  // 从队头移除元素
  removeFront() {
    if (this.isEmpty()) {
      return undefined;
    }
    const front = this.items[this.lowestCount];
    this.lowestCount++;
    return front;
  }

  // 从队尾移除元素
  removeBack() {
    if (this.isEmpty()) {
      return undefined;
    }
    return this.items[--this.count];
  }

  size() {
    return this.count - this.lowestCount;
  }

  toString() {
    let dequeString = "";
    if (this.isEmpty()) {
      return dequeString;
    }
    dequeString = `${this.items[this.lowestCount]}`;
    for (let i = this.lowestCount + 1; i < this.count; i++) {
      dequeString = `${dequeString},${this.items[i]}`;
    }
    return dequeString;
  }

  isEmpty() {
    return this.count - this.lowestCount === 0;
  }
}

// 使用双端队列检查回文字符串
function palindromeChecker(aString) {
  if (
    aString === undefined ||
    aString === null ||
    (aString !== null && aString.length === 0)
  ) {
    return false;
  }

  const deque = new Deque();
  // 处理字符串大小写、去除空格
  let lowerString = aString
    .toLocaleLowerCase()
    .split(" ")
    .join("");

  // 字符串都入队
  for (let i = 0; i < lowerString.length; i++) {
    deque.addBack(lowerString.charAt(i));
  }
  let isEqual = true;
  let lowChar;
  let hightChar;

  while (deque.size() > 1 && isEqual === true) {
    lowChar = deque.removeBack();
    hightChar = deque.removeFront();
    if (lowChar !== hightChar) {
      isEqual = false;
    }
  }
  return isEqual;
}

console.log("aa", palindromeChecker("aa"));
console.log("kayak", palindromeChecker("kayak"));
console.log("123214", palindromeChecker("123214"));