剑指Offer-- 两个栈模拟队列 替换空格

剑指Offer-- 两个栈模拟队列

 

 

 

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型

 

 

 

看代码:

#include<iostream>
#include<stack>
using namespace std;
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty()){
            while(!stack1.empty()){
              stack2.push(stack1.top());
              stack1.pop();
            }
        }

        int t =  stack2.top();
        stack2.pop();
        return t;

    }
    int front(){
        if(stack2.empty()){
            while(!stack1.empty()){
              stack2.push(stack1.top());
              stack1.pop();
            }
        }
        return stack2.top();
    }
    bool empty(){
        if(stack1.empty() && stack2.empty()){
            return true;
        }
        return false;
     }

private:
    stack<int> stack1;
    stack<int> stack2;
};
int main(){
    Solution S;
//    stack<int> s ;
//    s.push(1);
//    s.push(2);
//    s.push(3);
//    while(!s.empty()){
//        int n = s.top();
//        cout<<n<<endl;
//        s.pop();
//    }
     S.push(1);
     S.push(3);
     S.push(3);
     S.push(0);
     S.push(-1);
     while(!S.empty()){
         int n = S.front();
         cout<<n<<endl;
         S.pop();
     }
    return 0;
}

 

 

 

 

替换空格

 

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

 

不多说Java 实现  如果C实现 遍历字符串 if(str==“ ”)else{  s ="%20“”;}

 

代码:

 

public class replaceChar {
    
    public String replaceSpace(StringBuffer str) {
        String source = str.toString();
        source = source.replaceAll(" ", "%20");
        return source;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
           StringBuffer str = new StringBuffer("We are happy");
           String ans = new replaceChar().replaceSpace(str);
           System.out.println(ans);
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangxiaoming

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值