例题
1. 21.斐波那契数列
Acwing 21.斐波那契数列
![在这里插入图片描述](https://img-blog.csdnimg.cn/eb9db51c5ae84e9d959103df6e5adea6.png)
class Solution {
public:
int Fibonacci(int n) {
if(n <= 1) return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
};
2. 16.替换空格
Acwing 16.替换价格
class Solution {
public:
string replaceSpaces(string &str) {
string res;
for (auto c : str)
if (c == ' ') res += "%20";
else res += c;
return res;
}
};
3. 84.1+2+3+…+n
Acwing 84.1+2+3+…+n
class Solution {
public:
int getSum(int n) {
int res = n;
n > 0 && (res += getSum(n - 1));
return res;
}
};
4. 28.O(1)时间删除链表结点
Acwing 28.删除链表结点
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
5. 36.合并两个排序的链表
Acwing 36.合并两个排序的链表
![在这里插入图片描述](https://img-blog.csdnimg.cn/7dee8c91d59146e1a3d46f6e3ed2b999.png)
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
auto dumpy = new ListNode(-1), tail = dumpy;
while(l1 && l2)
if(l1->val < l2->val)
{
tail->next = l1;
tail = tail->next;
l1 = l1->next;
}
else
{
tail->next = l2;
tail = tail->next;
l2 = l2->next;
}
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return dumpy->next;
}
};
习题
1. 78.左旋转字符串(substr函数)
Acwing 78.左旋转字符串
![在这里插入图片描述](https://img-blog.csdnimg.cn/d0b75fb6f31d45828719e9bc19a3ea62.png)
- substr(start,length):从start开始,长度为length的子串
class Solution {
public:
string leftRotateString(string str, int n) {
return str.substr(n) + str.substr(0,n);
}
};
2. 87.把字符串转换成整数
Acwing 87.把字符串转换成整数
在这里插入代码片