劍指offer練習部分:替換空格,從尾到頭打印鏈表,棧模擬隊列

 替換空格,從尾到頭打印鏈表,棧模擬隊列,青蛙跳問題

請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。


class Solution {
public:
    char* Mstrcpy(char * des,const char* str)
{
    char * ret=des;
    while(*des++=*str++)
        ;
    return ret;
}
    void replaceSpace(char *str,int length) {
        string s(str);
        int i=0;
        while((i=s.find(' '))>-1){
            s.erase(i,1);
            s.insert(i,"%20");
             
        }
        const char* ret=s.c_str();
        Mstrcpy(str,ret);
    }
};

 利用stl中的erase和insert講空格替換

 

輸入一個鏈表,按鏈表值從尾到頭的順序返回一個ArrayList。

 

1思路    利用棧先入後出的特性完成

2思路    直接存入數組再reverse

class Solution {
public:
    
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> s;
        ListNode* cur=head;
        while(cur!=nullptr)
        {
            s.push(cur->val);
            cur=cur->next;
        }
        vector<int> v;
        while(s.empty()!=true)
        {
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }

 

 

用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素爲int類型

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack1.empty()&& stack2.empty())
            return -1;
        while(stack1.empty()==1)
        {
            int temp=stack1.top();
            stack1.pop();
            stack2.push(temp);
        }
        int ret=stack2.top();
        stack2.pop();
        return ret ;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

 大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項爲0)。

n<=39

class Solution {
public:
    int Fibonacci(int n) {
        if(n==0)
            return 0;
        if(n==1||n==2)
            return 1;
        int first=1,second=1;
        for(int i=2;i<n;i++)
        {
            int temp=second;
            second=first+second;
            first=temp;
            
        }
        return second;
    }
};

 一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。

 

class Solution {
public:
    int jumpFloor(int number) {
        //f1=1,f2=2 f3=3,f4=5
        int & n=number;
        if(n==1)
            return 1;
        auto first=1;
        auto second=1;
        for(int i=1;i<n;i++)
        {
            auto temp=second;
            second=first+second;
            first=temp;
            
        }
        return second;
    }
};

一隻青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。 

class Solution {
public:
    int jumpFloorII(int number) {
        return 1<<(number-1);
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章