首页 > 编程语言 > 详细

c++刷leetcode记录

时间:2021-05-01 16:31:13      阅读:17      评论:0      收藏:0      [点我收藏+]

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记录

原文:https://www.cnblogs.com/kongweisi/p/14724157.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!