LeetCode专辑]【1-5题】

本文解析了LeetCode上的几个经典算法题目,包括TwoSum、AddTwoNumbers、LongestSubstringWithoutRepeatingCharacters等,并提供了简洁高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一题:1. Two Sum

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        for(int i = 0; i < nums.size(); i++) {
            for(int j = i + 1; j < nums.size(); j++) {
                if(nums[i] + nums[j] == target) {
                    res.push_back(i);
                    res.push_back(j);
                }
            }
        }
        return res;
    }
};

第二题:2. Add Two Numbers
思路:分别把两个链表转换为整数x和y相加得到z然后把z转为链表。
开始用int储存通过一部分, 改为long long 通过1560 / 1562 test cases passed.
解这道题目陷入了自己挖的坑里面了, 用应该是简介的思路,最少的步骤去接问题,步骤越多可能增加许多不必的问题。
比如这个数的数据范围,unsigned变为负数时异常退出, 链表指针参数传递。

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        long long x = getNum(l1);
        long long y = getNum(l2);

        long long z = x + y;
        ListNode* head = NULL;
        build_list(z, head);
        return head;
    }
    long long getNum(ListNode* &L) {
         vector<int> num;
         while(L != NULL) {
            num.push_back(L->val);
            L = L->next;
         }
         long long sum = 0;
         for(int i = num.size()-1; i >= 0; i--) {
            sum = sum * 10 + num[i];
         }
         return sum;
    }
     void build_list(long long x, ListNode* &head) {
        vector<int> num;
        string str = int_to_string(x);
        for(int i = str.length()-1; i >= 0; i--) {
            num.push_back(str[i]-'0');
        }
        ListNode *lastPointer = NULL;
        for(unsigned i = 0; i < num.size(); i++) {
            if(i == 0) {
                head = new ListNode(num[i]);
                lastPointer = head;
            } else {
                lastPointer->next = new ListNode(num[i]);
                lastPointer = lastPointer->next;
            }
        }
    }
    //测试将数字转为链表用的
    void convertNumToList(long long x, ListNode* &head) {
        string str = int_to_string(x);
        ListNode *nextPoint = head;
        for(int i = str.length()-1; i >= 0; i--) {
            if(i == (int)str.length()-1) {
                head = new ListNode(str[i]-'0');
                nextPoint = head;
            } else {
                nextPoint->next = new ListNode(str[i]-'0');
                nextPoint = nextPoint->next;
            }
        }
    }
    string int_to_string(long long n) {
        ostringstream stream;
        stream << n;
        return stream.str();
    }
    //测试输出结果用的
    void output(ListNode* &h) {
        while(h != NULL) {
            cout << h->val << " ";
            h = h->next;
        }
        cout << endl;
    }
public:
    ListNode *head1 = NULL;
    ListNode *head2 = NULL;
};

int main()
{
    Solution *obj = new Solution();
    obj->convertNumToList(9, obj->head1);
    obj->output(obj->head1);
    obj->convertNumToList(9999999991, obj->head2);
    obj->output(obj->head2);
    ListNode *h = obj->addTwoNumbers(obj->head1, obj->head2);
    obj->output(h);
    return 0;
}

简介思路

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode(0);
        ListNode* tail = head;
        int sum = 0;
        while(l1 != NULL || l2 != NULL) {
            if(l1) {
                sum += l1->val;
                l1 = l1->next;
            }
            if(l2) {
                sum += l2->val;
                l2 = l2->next;
            }
            tail->next = new ListNode(sum%10);
            tail = tail->next;
            sum = sum/10;
        }
        if(sum == 1) {
            tail->next = new ListNode(1);
        }
        return head->next;
    }
};

数据:
Input:
[2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9]
[5,6,4,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9,9,9,9]
Output:
[9,0,4,4,6,9,7,4,9,4,2,7,8,8,6,2,6,9,7,-3]
Expected:
[7,0,8,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,1,4,3,9,1]

第三题:3. Longest Substring Without Repeating Characters

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
          int n = s.length();
          int i = 0, j = 0;
          int maxLen = 0;
          bool exist[256] = { false };
          while (j < n) {
                if (exist[s[j]-0]) {
                        maxLen = max(maxLen, j-i);
                        while (s[i] != s[j]) {
                                exist[s[i]-0] = false;
                                i++;
                        }
                        i++;
                        j++;
                } else {
                        exist[s[j]-0] = true;
                        j++;
                }
          }
          maxLen = max(maxLen, n-i);
          return maxLen;
        }
};

第五题:5. Longest Palindromic Substring

public class Solution {
    public  String longestPalindrome(String str) {
        StringBuilder sb = new StringBuilder();
        sb.append('#');
        char charArray[] = str.toCharArray();
        for(int i = 0; i < charArray.length; i++) {
            sb.append(charArray[i]);
            sb.append('#');
        }
        char mycharArray[] = sb.toString().toCharArray();
        int bestIndex = 0;
        int maxLength = -1;
        int radiusLength = 0;
        for(int i = 1; i < mycharArray.length; i++) {
            radiusLength = getLengthAndIndex(i, mycharArray);
            if(radiusLength > maxLength) {
                maxLength = radiusLength;
                bestIndex = i;
            }
        }
        String newString = sb.toString();
        int startIndex = bestIndex - maxLength + 1;
        int endIndex = bestIndex + maxLength;
        String subString = newString.substring(startIndex, endIndex);
        return subString.replace("#", "");
     }
     public  int getLengthAndIndex(int location, char[]mycharArray){
         int left = location;
         int right = location;
         int radiusLength = 0;
         while(left >= 0 && right < mycharArray.length) {
             if(mycharArray[left] == mycharArray[right]) {
                 radiusLength++;
                 left--;
                 right++;
             }else {
                 return radiusLength;
             }
         }
         return radiusLength;
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值