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;
}
};