[劍指Offer]---05替換空格與06從尾到頭打印鏈表

05替換空格

描述

請實現一個函數,把字符串 s 中的每個空格替換成"%20"。

 

示例 1:

輸入:s = "We are happy."
輸出:"We%20are%20happy."

 

限制:

0 <= s 的長度 <= 10000

思路

非空格則直接加入,空格則替換  時間複雜度O(n)  空時間複雜度O(n)

class Solution {
public:
    string replaceSpace(string s) {

        string ans;
        for (size_t i = 0; i < s.size(); i++)
        {
            if(s[i]!=' '){
                ans.push_back(s[i]);
            }
            else
            {
                ans.push_back('%');
                ans.push_back('2');
                ans.push_back('0');
            }
            
        }

        return ans;
        
        
    }
};

 

 

06從尾到頭打印鏈表

題目

輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。

 

示例 1:

輸入:head = [1,3,2]
輸出:[2,3,1]

 

限制:

0 <= 鏈表長度 <= 10000

思路

遍歷鏈表,將鏈表中的值放到一個棧(先進後出)中

時間複雜度O(n)  空時間複雜度O(n)


class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> ans;
        vector<int> res;
        ListNode* pNode = head;
        while (pNode!=nullptr)
        {
            ans.push(pNode->val);
            pNode=pNode->next;
        }

        while(!ans.empty()){
            res.push_back(ans.top());
            ans.pop();
        }

        return res;
        
    }
};

 

 

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