本文主要是介绍Leetcode刷题 2020.7.15,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
两数之和
这道题中的next指针的安排是重点。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode *h = l1, *p = l1;while(l1 || l2){if(!l1)p -> next = new ListNode(0), l1 = p -> next;//此行处理为重点!!!if(!l2)l2 = new ListNode(0);l1 -> val += l2 -> val;if(l1 -> val > 9){if(l1 -> next)l1 -> next -> val ++;else l1 -> next = new ListNode(1);l1 -> val %= 10;} p = l1; //注意保留之前的结点,防止之后的结点为空l1 = l1 -> next, l2 = l2 -> next;}return h;}
};
无重复的最长子串
运行错误的代码!!!
class Solution {
public:int lengthOfLongestSubstring(string s) {vector<int> ve(27, -1);int len = s.size(), t, Max = 0, k = 0;for (int i = 0; i < len; i++){t = s[i] - 'a';if(ve[t] == -1) ve[t] = i;else {Max = max(Max, i - k);for (int j = k; j < ve[t]; j++) ve[s[j] - 'a'] = -1;k = ve[t] + 1;ve[t] = i;}}if(!k) Max = len;return Max;}};
正解,滑动窗口!!!!!!!
class Solution {
public:int lengthOfLongestSubstring(string s) {unordered_map<char, int> tab;int len = s.size(), Max = 0, j = 0;for (int i = 0; i < len; i++){while(!tab.count(s[j]) && j < len) tab[s[j]] = 1, j++;if(j < len) tab.erase(s[i]);Max = max(Max, j - i);}return Max;}};
代码简化!!!!
class Solution {
public:int lengthOfLongestSubstring(string s) {unordered_map<char, int> tab; int len = s.size(), Max = 0;for (int i = 0, j = 0; j < len; j++){tab[s[j]]++;while(tab[s[j]] > 1) tab[s[i++]]--;Max = max(Max, j - i + 1);}return Max;}};
这篇关于Leetcode刷题 2020.7.15的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!