【剑指offer】05与06
1.面试题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 str;
int i=0;
while(i<s.length())
{
if(s[i]==' ') str+="%20";
else str+=s[i];
i++;
}
return str;
}
};
2.面试题06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
时间复杂度O(n),空间复杂度O(n)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> a;
while(head)
{
a.push_back(head->val);
head=head->next;
}
reverse(a.begin(),a.end());
return a;
}
};