Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对输入的字符串:去除其中的字符'b';去除相邻的'a'和'c'。 #119

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@mengqiuleo
Copy link

样例:

‘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'))

@bearki99
Copy link

补充:考虑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"));

@veneno-o
Copy link
Contributor

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"));

@renshengyiyijihe
Copy link

    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('')
    }

@kangkang123269
Copy link

function removeChars(str) {
    let stack = [];
    for (let i = 0; i < str.length; i++) {
        if (str[i] === 'b') continue;
        if ((str[i] === 'a' && stack[stack.length - 1] === 'c') || 
            (str[i] === "c" && stack[stack.length - 1] === "a")) {
            // 如果当前字符与堆栈顶部字符可以配对,则弹出顶部字符
            stack.pop();
        } else {
            // 否则将当前字符推入堆栈
            stack.push(str[i]);
        }
    }
    return stack.join('');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants