Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra chuỗi đã sắp xếp - JavaScript


Chúng ta cần viết hàm nhận vào chuỗi và kiểm tra xem nó có được sắp xếp hay không.

Ví dụ:

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

Ví dụ

Dưới đây là đoạn code:

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'; 
    }else if(findDiff(str[i+1], str[i]) < 0){ 
      res += 'd'; 
    }; 
    if(res.indexOf('u') && res.includes('d')){ 
      return false; 
    }; 
  }; 
  return true; 
}; 
console.log(isStringSorted(str));

Kết quả

Đoạn code sẽ in ra console:

true