Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การกำหนดสตริงตัวเลขที่สวยงาม (Beautiful) ใน JavaScript

สตริงตัวเลข str เรียกว่าสตริงสวยงาม (beautiful string) ถ้าสามารถแบ่งเป็นลำดับ arr ของจำนวนเต็มบวกสองตัวขึ้นไป ได้ที่ทำให้:

  • arr[i] - arr[i - 1] = 1 สำหรับทุก i ในดัชนีลำดับ คือแต่ละสมาชิกมากกว่าสมาชิกก่อนหน้า 1
  • ไม่มีสมาชิกในลำดับที่ขึ้นต้นด้วยศูนย์ นั่นคือ '50607' แบ่งเป็น [5, 06, 07] ได้ แต่ไม่สวยเพราะ 06 และ 07 นำหน้าด้วยศูนย์
  • เนื้อหาของลำดับไม่สามารถเรียงใหม่ได้

ตัวอย่าง

ถ้าสตริงนำเข้าคือ:

const str = '91011';

ผลลัพธ์ควรเป็น:

const output = true;

เพราะลำดับที่ต้องการคือ [9, 10, 11]

ตัวอย่างโค้ด

const str = '91011';
const isBeautiful = (str) => {
  let i = 1;
  let count = 0;
  const { length } = str;
  while(i <= length / 2) {
    let check = true;
    let j = i;
    let left = BigInt(str.substring(0, j));
    let nextRange = (left + 1n).toString().length;
    while(j + nextRange <= length) {
      let right = BigInt(str.substring(j, j + nextRange));
      if(left === right - 1n) {
        left = right;
        j += nextRange;
        nextRange = (left + 1n).toString().length;
        count = j;
      } else {
        check = false;
        break;
      }
    }
    if(check === true && count === length) {
      return true;
    }
    i++;
  }
  return false;
};
console.log(isBeautiful(str));

ผลลัพธ์

true