检查字符串是否在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';
}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));输出结果
这将在控制台中产生以下输出-
true
热门推荐
6 怎么说祝福语简短
10 新年祝福语简短聪明可爱
11 周年蛋糕祝福语简短英语
12 元旦的祝福语简短 公司
13 春天变冷祝福语简短
14 永远漂亮祝福语女生简短
15 中秋快乐祝福语简短的
16 十月简短祝福语
17 出阁祝福语简短句子
18 过节文案成语祝福语简短