两数相加-中等
之前做过类似的题,可以自己写出来。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int lastValue=0;
int value;
ListNode* preHead=new ListNode();
ListNode* pre =preHead;
while(l1!=nullptr || l2!=nullptr){
if(l2==nullptr){
value =(l1->val+lastValue)%10;
lastValue=(l1->val+lastValue)/10;
pre->next=new ListNode(value);
pre = pre->next;
l1=l1->next;
}else if(l1==nullptr){
value =(l2->val+lastValue)%10;
lastValue=(l2->val+lastValue)/10;
pre->next=new ListNode(value);
pre = pre->next;
l2=l2->next;
}else{
value =(l1->val+l2->val+lastValue)%10;
lastValue=(l1->val+l2->val+lastValue)/10;
pre->next=new ListNode(value);
pre = pre->next;
l1=l1->next;
l2=l2->next;
}
}
if(lastValue!=0){
pre->next =new ListNode(lastValue);
}
return preHead->next;
}
};
无重复字符的最长子串-中等
这题看了答案才做出来,关键是要发现规律并借助集合的特性。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> st;
int ans=0;
int end=-1;
for(int i=0;i<s.size();i++){
if(i!=0){
st.erase(s[i-1]);
}
while(end+1<s.size() && !st.count(s[end+1])){
end++;
st.insert(s[end]);
}
ans=max(ans,end-i+1);
}
return ans;
}
};