Loading

12.16

456. 132模式

难度中等

给定一个整数序列:a1, a2, ..., an,一个132模式的子序列 ai, aj, ak 被定义为:当 i < j < k 时,ai < ak < aj。设计一个算法,当给定有 n 个数字的序列时,验证这个序列中是否含有132模式的子序列。

注意:n 的值小于15000。

示例1:

输入: [1, 2, 3, 4]

输出: False

解释: 序列中不存在132模式的子序列。

示例 2:

输入: [3, 1, 4, 2]

输出: True

解释: 序列中有 1 个132模式的子序列: [1, 4, 2].

示例 3:

输入: [-1, 3, 2, 0]

输出: True

解释: 序列中有 3 个132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0].

解答 : 不同于一般的单调栈,这次 遍历是从右往左遍历,当维护的栈的栈顶小于下一个遍历的数时,弹出栈顶元素

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        stack<int>stk;
        int n = nums.size();
        int res = INT_MIN;
        for(int i = n - 1; i >= 0; i--){
            if(nums[i] < res)return true;
            while(stk.size() && nums[i] > stk.top()){
                res = max(res, stk.top());
                stk.pop();
            }
            stk.push(nums[i]);
        }
        return false;
    }
};

290. 单词规律

难度简单282

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

示例1:

输入: pattern = "abba", str = "dog cat cat dog"
输出: true

示例 2:

输入:pattern = "abba", str = "dog cat cat fish"
输出: false

示例 3:

输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false

示例 4:

输入: pattern = "abba", str = "dog dog dog dog"
输出: false

说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<string>words;
        unordered_map<char, string>cw;
        unordered_map<string, char>sw;
        stringstream ssin(s);
        string word;
        while(ssin >> word)words.push_back(word);
        if(words.size() != pattern.size())return false;
        for(int i = 0; i < pattern.size(); i++){
            auto a = pattern[i];
            auto b = words[i];
            if(cw.count(a) && cw[a] != b)return false;
            cw[a] = b;
            if(sw.count(b) && sw[b] != a)return false;
            sw[b] = a;
        }
        return true;
    }
};
posted @ 2020-12-16 23:09  桥木  阅读(113)  评论(0)    收藏  举报