0
点赞
收藏
分享

微信扫一扫

Net常用类整理

TiaNa_na 2024-04-12 阅读 7

3. 无重复字符的最长子串 - 力扣(LeetCode)
image.png
双指针,l和r从字符串最左边开始,保存l和r之间的所有字符
移动r,若新加入的字符和已有字符重复,则不断移动l,直到l和r之间不出现重复字符
注意:移动的过程中需要维护l和r之间的字符
每次移动完r并保证l和r之间无重复字符,则维护ans

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int l = 0, r = 0;
        int ans = 0;
        set<char> ss;
        while (r < s.size()) {
            if (ss.count(s[r])) {
                while (s[l] != s[r]) {
                    ss.erase(s[l]);
                    l ++ ;
                } 
                l ++ ;
            }
            ss.insert(s[r]);
            ans = max(ans, r - l + 1);
            r ++ ;
        }
        return ans;
    }
};

84. 柱状图中最大的矩形 - 力扣(LeetCode)
image.png

解题的关键在于最小的柱子,对所有柱子进行排序,假设当前柱子的高度为h,则不用考虑高度大于h的柱子,考虑高度小于h的柱子
那么能勾勒的最大矩形为,以:向左第一个小于h的柱子与向右第一个小于h的柱子为底,高为h的矩形
从最小高度开始查找最大矩形,即可

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        vector<pair<int, int>> a;
        for (int i = 0; i < heights.size(); ++ i) {
            a.push_back({heights[i], i});
        }
        sort(a.begin(), a.end());
        set<int> s;
        s.insert(-1), s.insert((int)heights.size());
        int ans = 0;
        for (int i = 0; i < a.size(); ++ i) {
            // 根据柱子的位置找左右边界
            int l = *(prev(s.lower_bound(a[i].second)));
            int r = *(s.upper_bound(a[i].second));
            ans = max(ans, a[i].first * (r - l - 1));
            s.insert(a[i].second);
        }
        return ans;
    }
};
举报

相关推荐

.Net常用模块类

常用技巧整理

常用函数整理

常用算法整理

File类整理

常用 ASCII 码整理

常用mysql语句整理

0 条评论