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

การตรวจสอบลำดับการจัดเรียงสตริงใน JavaScript

บทความนี้สาธิตวิธีเขียนฟังก์ชัน JavaScript เพื่อตรวจสอบว่าสตริงถูกจัดเรียงตามลำดับตัวอักษร (อั่งกะไปหรือถอยหลัง) หรือไม่

ตัวอย่าง

isSorted('adefgjmxz') // true
isSorted('zxmfdba')   // true
isSorted('dsfdsfva')  // false

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

const str = 'abdfhlmxz';

const findDiff = (a, b) => a.charCodeAt(0) - b.charCodeAt(0);

const isStringSorted = (str = '') => {
  if (str.length < 2) {
    return true;
  }
  let res = '';
  for (let i = 0; i < str.length - 1; i++) {
    if (findDiff(str[i + 1], str[i]) > 0) {
      res += 'u'; // up
    } else if (findDiff(str[i + 1], str[i]) < 0) {
      res += 'd'; // down
    }
    if (res.indexOf('u') !== -1 && res.includes('d')) {
      return false;
    }
  }
  return true;
};

console.log(isStringSorted(str));

ผลลัพธ์

true

คำอธิบาย

ฟังก์ชันเปรียบเทียบค่า charCode ของตัวอักษรที่ติดกัน สร้างสตริง 'res' บันทึกทิศทาง ('u' = เพิ่ม, 'd' = ลด) หากพบทั้ง 'u' และ 'd' แสดงว่าลำดับไม่สม่ำเสมอ จะคืนค่า false ทันที

สตริง 'abdfhlmxz' จัดเรียงจากน้อยไปมาก (up เท่านั้น) จึงคืนค่า true