替换空格,从尾到头打印链表,栈模拟队列,青蛙跳问题
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
char* Mstrcpy(char * des,const char* str)
{
char * ret=des;
while(*des++=*str++)
;
return ret;
}
void replaceSpace(char *str,int length) {
string s(str);
int i=0;
while((i=s.find(' '))>-1){
s.erase(i,1);
s.insert(i,"%20");
}
const char* ret=s.c_str();
Mstrcpy(str,ret);
}
};
利用stl中的erase和insert讲空格替换
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
1思路 利用栈先入后出的特性完成
2思路 直接存入数组再reverse
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> s;
ListNode* cur=head;
while(cur!=nullptr)
{
s.push(cur->val);
cur=cur->next;
}
vector<int> v;
while(s.empty()!=true)
{
v.push_back(s.top());
s.pop();
}
return v;
}
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack1.empty()&& stack2.empty())
return -1;
while(stack1.empty()==1)
{
int temp=stack1.top();
stack1.pop();
stack2.push(temp);
}
int ret=stack2.top();
stack2.pop();
return ret ;
}
private:
stack<int> stack1;
stack<int> stack2;
};
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
class Solution {
public:
int Fibonacci(int n) {
if(n==0)
return 0;
if(n==1||n==2)
return 1;
int first=1,second=1;
for(int i=2;i<n;i++)
{
int temp=second;
second=first+second;
first=temp;
}
return second;
}
};
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
class Solution {
public:
int jumpFloor(int number) {
//f1=1,f2=2 f3=3,f4=5
int & n=number;
if(n==1)
return 1;
auto first=1;
auto second=1;
for(int i=1;i<n;i++)
{
auto temp=second;
second=first+second;
first=temp;
}
return second;
}
};
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
class Solution {
public:
int jumpFloorII(int number) {
return 1<<(number-1);
}
};