day06使用两个栈实现一个队列+使用两个队列实现一个栈+字符串空格替换
2017-07-18 23:41
417 查看
1.使用两个栈实现一个队列
使用两个队列实现一个栈
替换字符串中的空格为$$$。要求时间复杂度为O(N)
class Queue { public: void Push(int val) { s1.push(val); } void Pop() { assert(s1.size() || s2.size()); if(s2.empty()) { while(!s1.empty()) { int temp = s1.top(); s2.push(temp); s1.pop(); } } s2.pop(); } int Front() { assert(s1.size() || s2.size()); if(s2.empty()) { while(!s1.empty()) { int temp = s1.top(); s2.push(temp); s1.pop(); } } return s2.top(); } private: stack<int> s1; stack<int> s2; };
使用两个队列实现一个栈
class Stack { public: void Push(int val) { q1.push(val); } void Pop() { assert(q1.size()); //一定要有元素才能出栈操作。 while(q1.size() != 1) { q2.push( q1.front() ); q1.pop(); } q1.pop(); swap(q1, q2); //交换队列,q2就是一个辅助队列, } int Top() { assert(q1.size()); return q1.back(); } private: queue<int> q1; queue<int> q2; };
替换字符串中的空格为$$$。要求时间复杂度为O(N)
例如:将"talk is cheap show me the code"替换。为"talk$$$is$$$cheap$$$show$$$me$$$the$$$code"。
void ReplaceSpace(char *str) { assert(str); char *pcur = str; int spacenum = 0; while(*pcur != '\0') { if( isspace(*pcur) ) { spacenum++; } pcur++; } char *ptail = str+strlen(str); char *pnewtail = ptail+2*spacenum; while(ptail != pnewtail) { *pnewtail = *ptail; if( isspace(*pnewtail) ) { *pnewtail-- = '$'; *pnewtail-- = '$'; *pnewtail-- = '$'; ptail--; } else { pnewtail--; ptail--; } } }
相关文章推荐
- 使用两个栈实现一个队列/使用两个队列实现一个栈/空格替换
- 使用正则表达式将一个字符串中连续的多个(两个或者两个以上)替换为一个空格
- 013使用两个栈实现一个队列(keep it up)
- 【题目5】如何使用两个栈来实现一个队列
- }1.字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“we are happy.”,则输出“we%20are%20happy.”。
- 【我的算法日记】请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
- 使用两个队列实现一个栈,使用两个栈实现一个队列!
- 【C语言】【面试题】【笔试题】.字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”。
- 【c语言】字符串替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”
- 实现一个函数,将字符串的每一个空格替换成 %20
- 算法导论 使用两个队列实现一个栈
- 实现一个函数,将一个字符串中的空格替换成“ % 20”
- [剑指offer][面试题04]实现一个函数,将字符串中的空格替换为“ ”.例如输入“we are happy.”,输出"we are happy.".
- 请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
- 替换空格-请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 使用两个队列实现一个栈,使用两个栈实现一个队列!
- 请实现一个函数,把字符串中的每个空格替换成“%20”,例如输入 “We are Happly。” 则输出“we%20are%20happy。”
- 请实现一个函数,把字符串中的每个空格替换成“%20”
- 【C语言】字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”
- 使用两个队列实现一个栈