javascript - 按字母顺序取消连续字符的资格。Sol [ASCII 格式]
问题描述
我的朋友给了我这个问题。该问题要求从给定的字符串输入中删除所有按字母顺序排列的连续字符。所以我使用 Javascript 完成了它,如果我准确地执行它,我需要专家帮助。
我认为使用 Array.prototype.reduce 将是最好的方法,我们还有其他可能的方法吗?
/**
* @author Abhishek Mittal <abhishekmittaloffice@gmail.com>
* @description function can deal with both any types followed in a consecutive manner in ASCII Chart.
* @param {string} str
*/
function improvise(str) {
// Backup for original input.
const bck = str || '';
const bckArr = bck.split('').map( e => e.charCodeAt(0)); // converting the alphabets into its ASCII for simplicity and reducing the mayhem.
let result = bckArr.reduce( (acc, n) => {
// Setting up flag
let flag1 = n - acc.rand[acc.rand.length - 1];
let flag2 = n - acc.temp;
if(flag1 === 1 || flag2 === 1) {
(flag2 !== NaN && flag2 !== 1) ? acc.rand.pop() : null; // update the latest value with according to the case.
acc.temp = n
}else{
acc.rand.push(n); // updating the random to latest state.
acc.temp = null;
}
return acc;
}, {rand: [], temp: null} /* setting up accumulative situation of the desired result */)
result = result.rand.map(e => String.fromCharCode(e)).join('')
return result ? result : '' ;
}
function init() {
const str = "ab145c";
const final = improvise(str);
console.log(final)
}
init();
好吧,输出结果是正确的。输入:ab145c 输出:1c
解决方案
不幸的是,没有办法使用任何远程合理的正则表达式来解决这个问题。
我认为使用会更清楚.filter
,并检查下一个字符或前一个字符是否连续:
const code = char => char
? char.charCodeAt(0)
: -2; // will not be === to any other codes after addition or subtraction
function improvise(str) {
return [...str]
.filter((char, i) => {
const thisCode = code(char);
return (
thisCode !== code(str[i - 1]) + 1
&& thisCode !== code(str[i + 1]) - 1
);
})
.join('');
}
console.log(improvise('ab145c'));
(或者,您可以只检查下一个字符是否连续,但您还必须检查字符串中最后一个字符的有效性)
如果您需要连续替换字符直到没有连续的字符,请继续调用improvise
:
const code = char => char
? char.charCodeAt(0)
: -2; // will not be === to any other codes after addition or subtraction
function improvise(str) {
return [...str]
.filter((char, i) => {
const thisCode = code(char);
return (
thisCode !== code(str[i - 1]) + 1
&& thisCode !== code(str[i + 1]) - 1
);
})
.join('');
}
let result = 'hishakmitalaaaaabbbbbbcccccclmnojqyz';
let same = false;
while (!same) {
const newResult = improvise(result);
if (newResult !== result) {
result = newResult;
console.log(result);
} else {
same = true;
}
}
console.log('FINAL:', result);
推荐阅读
- c# - 具有多个不同类型参数的 Dapper 更新查询
- python - 我正在尝试使用 python 从 aws 下载整个 s3 存储桶,但得到一个 OSError[error22]
- angular - 内容安全政策指令
- javascript - 服务人员什么时候应该自毁?
- reactjs - 有条件地将 prop 传递给 React 中的组件
- r - 无法在 R 中创建印度等值线
- java - 自定义订购 MSSQL 休眠 Spring Boot 2
- google-bigquery - BigQuery Avro 加载作业与 useAvroLogicalTypes 不正确的字段类型
- ios - SwiftUI:向控件添加效果会禁用交互性
- c# - 绑定:未找到属性。MVVM