力扣刷题代码巧解:
删除链表的倒数第n个节点:
通过递归的方式删除节点;
class Solution {
public:
int cur=0;
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return NULL;
head->next=removeNthFromEnd(head->next,n);
cur++;
if(cur==n) return head->next;
return head;
}
};
最长公共前缀:
通过字符串ASCII码值比较的规则排序,比较开头末尾的公共前缀;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
sort(strs.begin(),strs.end());
string s1=strs[0],s2=strs.back();
int i=0;
int len=min(s1.size(),s2.size());
while(i<len&&s1[i]==s2[i]) i++;
return string(s1.begin(),s1.begin()+i);
}
};
最长回文子串:
以一个或者两个字符为中心向外扩散,判断回文;
class Solution {
public:
int l=0;
int r=0;
int maxlen=0;
string longestPalindrome(string s) {
for(int i=0;i<s.length();i++){
int j=i,k=i;
while(j>=0&&k<s.length()&&s[j]==s[k]){
if(k-j+1>maxlen) {
maxlen=k-j+1;
l=j;
}
j--;k++;
}
j=i;k=i+1;
while(j>=0&&k<s.length()&&s[j]==s[k]){
if(k-j+1>maxlen) {
maxlen=k-j+1;
l=j;
}
j--;k++;
}
}
return s.substr(l,maxlen);
}
};
三数之和:
双指针遍历;
合并链表(递归):
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1->val<l2->val) {
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else {
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
};
电话号码的数字组合(回溯法):
class Solution {
public:
string m[10]={
"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"
};
vector<string> res;
string s;
void dfs(const string& digits,int index) {
if(index==digits.size()){
res.push_back(s);
return;
}
int d=digits[index]-'0';
string str=m[d];
for(int i=0;i<str.size();i++){
s.push_back(str[i]);
dfs(digits,index+1);
s.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.size()==0) return res;
dfs(digits,0);
return res;
}
};