-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
Comments
样例: ‘aacbd’ -> 'ad' 'aabcd' -> 'ad' 'aaabbccc' -> '' 不允许使用类似string.replace函数 思路:使用栈 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")); |
|
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
No description provided.
The text was updated successfully, but these errors were encountered: