仅使用栈基本操作时,如何避免栈元素重复并完成字符串提取任务?
问题指引请求
任务需求
- 从目标字符串中提取所有元音、数字和符号,分别存入对应的
vowel stack、digit stack、symbol stack - 提取完成后,依据字符串中的最后一个symbol,对digit stack的前两个元素(即字符串中最后出现的两个数字)执行算术运算
约束条件
- 各栈中不能存在重复元素
- 禁止使用vector记录已使用的字符,仅允许调用栈的基础操作:
push()、pop()、isEmpty()、peek()、isFull()
当前困惑
之前尝试编写find方法遍历栈来检查元素是否存在,但这种方式需要弹出栈内所有元素,会破坏后续对digit和symbol栈的操作,现在不知道该怎么处理重复元素的校验,希望得到方向指引。
原参考代码
// traverse through the string for (int i = 0; i < toParse.length(); i++) { // if the char is a vowel, add it to the vowel stack (if it's not already in the stack) if(isVowel(toParse[i]) == true) { if(find(used.begin(), used.end(), tolower(toParse[i])) == used.end()) { vowels.push(tolower(toParse[i])); used.push_back(tolower(toParse[i])); } } // if the char is a digit, add it to the digit stack (if it's not already there) if(isdigit(toParse[i])) { if(find(used.begin(), used.end(), toParse[i]) == used.end() ) { digits.push(atoi(&toParse[i])); used.push_back(toParse[i]); } } // if the char is a symbol, add it to the symbol stack regardless of whether it's already there or not if(isSymbol(toParse[i])) { if(find(used.begin(), used.end(), toParse[i]) == used.end() ) { symbols.push(toParse[i]); used.push_back(toParse[i]); } } }
内容的提问来源于stack exchange,提问作者butterfly549
相关产品推荐
相关产品推荐

