c++刷leetcode记录

2021/5/1 14:55:09

本文主要是介绍c++刷leetcode记录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

3. 无重复字符的最长子串

#include <iostream>
#include <unordered_set>


class Solution {
public:
    int lengthOfLongestSubstring(std::string s) {
        int length = s.size();
        int maxLength = 0;
        int lastMaxLength = 0;
        std::unordered_set<char> unorderedSet;
        //std::set<int> set;

        for (int i = 0; i < length; ++i) {
            unorderedSet.clear();
            for (int j = i; j < length; ++j) {
                if (unorderedSet.find(s[j]) != unorderedSet.end()) {
                    break;
                }
                unorderedSet.insert(s[j]);
                int nowLength = unorderedSet.size();
                maxLength = nowLength > lastMaxLength ? nowLength : lastMaxLength;
            }
            lastMaxLength = maxLength;
        }
        return maxLength;
    }
};

 

49. 字母异位词分组

#include <iostream>
#include <vector>
#include <unordered_set>
#include <map>
#include <algorithm>

/* 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

 */

class Solution {
public:
    std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) {
        std::map<std::string, std::vector<std::string>> map;
        for (auto ss: strs) {
            std::string value = ss;
            std::sort(ss.begin(), ss.end());
            map[ss].push_back(value);
        }

        std::vector<std::vector<std::string>> ret;
        for (auto it = map.begin(); it != map.end(); it++) {
            ret.push_back(it->second);
        }

        return ret;
    }
};

 

86. 分隔链表

/**
 * 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* partition(ListNode* head, int x) {
        ListNode* small = new ListNode(0);
        ListNode* smallHead = small;
        ListNode* large = new ListNode(0);
        ListNode* largeHead = large;

        while (head != nullptr) {
            if (head->val < x) {
                small->next = head;
                small = small->next;

            } else {
                large->next = head;
                large = large->next;
            }

            head = head->next;
        }

        large->next = nullptr;
        small->next = largeHead->next;

        return smallHead->next;

    }
};

 



这篇关于c++刷leetcode记录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程