对输入的字符串:去除其中的字符'b';去除相邻的'a'和'c'。
Sunny-117 opened this issue · comments
对输入的字符串:去除其中的字符'b';去除相邻的'a'和'c'。
样例:
‘aacbd’ -> 'ad'
'aabcd' -> 'ad'
'aaabbccc' -> ''
不允许使用类似string.replace函数
对输入的字符串:去除其中的字符'b';去除相邻的'a'和'c'。
思路:使用栈
function removeStr(str){
let stack = [];
for(let ch of str){
if(ch=='b') continue;
if(ch!=='c'){
stack.push(ch);
}
if(stack.length && stack[stack.length-1]=='a' && ch=='c'){
stack.pop();
}
}
return stack.join('');
}
console.log(removeStr('aaabbccc'))
补充:考虑c在前,a在后的情况
function removeStr(str) {
const stk = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === "b") continue;
else if (!stk.length) stk.push(str[i]);
else {
if (stk.length && str[i] === "a" && stk[stk.length - 1] == "c") stk.pop();
else if (stk.length && str[i] === "c" && stk[stk.length - 1] == "a") stk.pop();
else stk.push(str[i]);
}
}
return stk.join("");
}
console.log(removeStr("cccbbaaa"));
function format(str){
const stack = [], len = str.length;
for(let i = 0; i < len; ++i){
if(str.charAt(i) === "b"){
continue;
}else if(stack.length > 0 && ((stack[stack.length - 1] === "a" && str.charAt(i) === "c") || (stack[stack.length - 1] === "c" && str.charAt(i) === "a"))){
stack.pop();
continue;
}
stack.push(str.charAt(i));
}
return stack.join("");
}
console.log(format("agjaibasfccasdfaaaccc"));
const removeStr = (str) => {
const s = []
for (let c of str) {
if (c == 'b') continue;
if (c == 'c' && s.length && s[s.length - 1] == 'a') s.pop()
else s.push(c)
}
return s.join('')
}