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