• 567. Permutation in String


    问题描述:

    Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

    Example 1:

    Input: s1 = "ab" s2 = "eidbaooo"
    Output: True
    Explanation: s2 contains one permutation of s1 ("ba").
    

    Example 2:

    Input:s1= "ab" s2 = "eidboaoo"
    Output: False
    

    Note:

    1. The input strings only contain lower case letters.
    2. The length of both given strings is in range [1, 10,000].

    解题思路:

    这道题让我们在一个字符串s2里面去找另一个字符串s1的排列。

    并且是作为子串出现,这代表必须是连续的。

    找另一个字符串s1的排列,可以对s1用hashmap进行统计,统计没个characters出现的次数。(如果只有字母的话,可以使用静态数组来存储, 空间会变成O(1))

    因为要子串,我们可以用滑动窗口配合解决:

      对当前在s2遇见的字符c有以下几种可能:

      1. c 没有出现在s1中 ------> 移动左边界到右边界。

      2. c 出现在s1中:

        a. c之前出现过s1中出现的次数了(m1[c] == 0)---->将左边界移动至m1[c] 不为零的位置。

        b. 还没有出现够次数---> 移动右边界

    代码:

    class Solution {
    public:
        bool checkInclusion(string s1, string s2) {
            unordered_map<char, int> m1;
            for(char c : s1){
                m1[c]++;
            }
            int l = 0, r = 0;
            while(l < s2.size() && r < s2.size() && l <= r){
                if(m1.count(s2[r]) == 0){
                    while(l < r){
                        ++m1[s2[l]];
                        ++l;
                    }
                    ++r;
                    ++l;
                }else if( m1[s2[r]] == 0){
                    while(l < r && m1[s2[r]] == 0){
                        ++m1[s2[l]];
                        ++l;
                    }
                }else{
                    --m1[s2[r]];
                    ++r;
                    if(r-l == s1.size())
                        return true;
                }
            }
            return false;
        }
    };

    时间复杂度 O(n), 空间 O(n)

  • 相关阅读:
    session、cookie、token
    跨域问题-nginx代理
    跨域问题-jsonp
    fat32转ntfs
    nginx日志输出,https,ssl
    nginx安装
    MySql(一)表类型(存储引擎)
    ShowDoc,APIDoc,可道云API,语雀-适合IT企业的文档工具
    Docker Compose搭建Redis一主二从三哨兵高可用集群
    Docker容器启动Mysql,Docker实现Mysql主从,读写分离
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/11633295.html
Copyright © 2020-2023  润新知