[研究生冲刺][算法实习生]LeetCode刷题日记(Day10)【欢迎关注,一起努力!Cheers!】
剑指 Offer 05. 替换空格
思路:
这是一个easy的题目,直接创建一个空string res,让如果s[i] 为空格则依次在res的后面加上 ‘%’ , ‘2’ , ‘0’,否则直接加上s[i]。
算法的复杂度:
此算法时间复杂度为O(n)。
代码:
class Solution {
public:
string replaceSpace(string s) {
string res;
for(int i = 0;i < s.size(); ++i)
{
if(s[i] == ' ')
{
res.push_back('%');
res.push_back('2');
res.push_back('0');
}
else
{
res.push_back(s[i]);
}
}
return res;
}
};
剑指 Offer 06. 从尾到头打印链表
思路:
此题在每次遍历时将新元素放到vector的开头即可。
算法的复杂度:
此算法时间复杂度为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> res;
while(head)
{
res.insert(res.begin(), head->val);
head = head->next;
}
return res;
}
};