反转字符串


问题:用O(n)的算法把"www.taobao.com"转成"com.taobao.www"

方法:

用两个栈

从左至右扫描字符串,以点号为分隔符,每次扫描到点号的时候就把前面的字符压栈到s1,

然后再一直吧s1里的东西弹栈到s2,一直弹到s1空为止

中间过程中弄几个标记变量保存数组指针,

最后把s2里的东西从栈顶一直弹出来输出直到s2为空就可以了

代码如下:

#include<iostream>
#include<cstring>
#define SIZE 20
using namespace std;


class Stack
{
private:
	char stack[SIZE];
	int top;
public:
   Stack()
   {
    top=-1;
   }
   ~Stack()
   {
   }
   void push(char x)
   {
    top++;
    stack[top] = x;
   }
   char pop()
   {
    return stack[top--];
   }
	bool isempty()
	{	if(top==-1)
			return true;
		else
			return false;
	}
	bool isfull()
	{
		if(top==SIZE)
			return true;
		else
			return false;
	}

};


int main()
{
	char str[] = "www.taobao.com";
	int i,j;
	Stack s1;
	Stack s2;
	int temp;
	int flag = 0;
	for(i = 0 ;i <= strlen(str);i++)
	{
		if(str[i]=='.'||str[i]=='\0')
			{
				temp = i;
				for(j = flag; j<temp ;j++ )
				{
					s1.push(str[j]);	
				}
				while(!s1.isempty())
				{
					s2.push(s1.pop());
				}
				flag = temp + 1;
				s2.push('.');
			}

	}
	
	s2.pop();
	while(!s2.isempty())
		{
			cout<<s2.pop();
		}
		cout<<endl;


}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值