继续刷题!
二十一 合并两个有序链表
二十二 括号生成
二十六 删除排序数组中的重复项
二十七 移除元素
二十八 实现strStr()
二十一 合并两个有序链表
我是把第二条链往第一条链上加的,然后我终于会构造空的头了!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode * front=new ListNode(0);
ListNode * temp =front;
front->next=l1;
while(l1!=NULL&&l2!=NULL){
if(l2->val<l1->val){
ListNode * temp2=l2;
front->next=temp2;
l2=l2->next;
temp2->next=l1;
front=front->next;
}else{
l1=l1->next;
front=front->next;
}
}
if(l2!=NULL){
front->next=l2;
}
return temp->next;
}
};
二十二 括号生成
哦豁,这是道递归题啊,想了想,递归结束的条件肯定是符合条件的括号都被用上了(字符串的长度为n的二倍)
然后。。。嗯,主要就是在每一次递归的过程中选“(”还是选“)”这个的问题了,我居然用了两个栈(一个left,一个right)来分别存取n个左括号和右括号,然后我的判断条件居然都是(!stack.empty()),然后执行完我一看好家伙,只有一种结果,大家猜到了吗,这是必然的。。。
然后我就不知道了,看了题解果然又豁然大悟!!!
以下是官方题解(open和close来分别限制左括号和右括号的数量):
class Solution {
public:
vector<string>ans;
void generateKuoHao(int target,string temp,int open,int close){
if(temp.length()==target*2){
ans.push_back(temp);
return;
}
if(open<target){
generateKuoHao(target,temp+"(",open+1,close);
}
if(close<open){
generateKuoHao(target,temp+")",open,close+1);
}
}
vector<string> generateParenthesis(int n) {
generateKuoHao(n,"",0,0);
return ans;
}
};
递归啊!!!
二十六 删除排序数组中的重复项
这题嘛,不过题目中给的是vector,从一开始有重复的就挨着删(erase函数方便)就好了,所以我们需要知道vector的删除和迭代遍历
我是看了这篇博客https://blog.csdn.net/f156207495/article/details/82937853(非常感谢!)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0){
return 0;
}else{
for(vector<int>::iterator iter=nums.begin(); iter!=nums.end()-1; )
{
if(iter==nums.end()){
break;
}
if( *iter == *(iter+1))
nums.erase(iter+1);
else
iter ++ ;
}
return nums.size();
}
}
};
我感觉最神奇的就是iter!=nums.end()-1这里了,迭代器居然可以这样来用!
二十七 移除元素
这题我就不说了
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for(vector<int>::iterator iter=nums.begin(); iter!=nums.end(); )
{
if(*iter == val)
nums.erase(iter);
else
iter ++ ;
}
return nums.size();
}
};
二十八 实现strStr()
我们注意:题目中告诉了我们一个很重要的信息
当needle是空字符串时,我们应当返回什么值呢?我们应当返回0,这与C语言的strstr()以及Java的indexOf()定义相符
这题我们不用KMP了。。直接用C++自带的两个函数就好了,一个是题目中提到的strstr(),一个是find()函数
strstr()见这篇博客吧https://blog.csdn.net/yf_li123/article/details/71333701
find()见这篇博客吧https://www.cnblogs.com/wkfvawl/p/9429128.html
两者之间的简明区别:https://blog.csdn.net/l_vaule/article/details/40078343
strstr():
class Solution {
public:
int strStr(string haystack, string needle) {
int ans=-1;
if(needle==""){
return 0;
}
const char*p1 = strstr(haystack.c_str(), needle.c_str());
if(p1==NULL){
ans=-1;
}else{
ans=p1-haystack.c_str();
}
return ans;
}
};
find():
class Solution {
public:
int strStr(string haystack, string needle) {
int ans=-1;
if(needle==""){
return 0;
}
ans=haystack.find(needle);
return ans;
}
};