zoukankan      html  css  js  c++  java
  • 567. Permutation in String字符串的排列(效率待提高)

    网址:https://leetcode.com/problems/permutation-in-string/

    参考:https://leetcode.com/problems/permutation-in-string/discuss/102588/Java-Solution-Sliding-Window

    把s1的各个字母的出现次数记录下来,对s2利用滑动窗口法,逐步移动窗口,判断当前窗口内字符串是否是s1的全排列之一。
    容易想到,窗口内的字符对应的出现次数要-1。所以,当字符从窗口左端脱离窗口时,要+1;当字符从窗口右端进入窗口时,要-1。

    class Solution
    {
    public:
        bool allZero(vector<int> count) // 检查count是否全零
        {
            for(int i : count)
            {
                if( i != 0)
                    return false;
            }
            return true;
        }
        
        bool checkInclusion(string s1, string s2)
        {
            int len1 = s1.size();
            int len2 = s2.size();
            // if s1 is longer than s2, the answer is definitely false
            if(len1 > len2)
                return false;
            
            // 用于保存26个字母的使用情况
            vector<int> count(26, 0);
            for(int i=0; i<len1; i++)
            {
                // 将s1的各个字母使用次数加 1
                count[s1[i] - 'a']++;
                // 此语句实际上为滑动窗口的初始化
                count[s2[i] - 'a']--;
            }
            // 判断第一个滑动窗口
            if(allZero(count))
                return true;
            
            // 移动滑动窗口
            for(int i=len1; i<len2; i++)
            {
                // 
                count[s2[i] - 'a']--;
                count[s2[i-len1] - 'a']++;
                // 检查是否全零。全零代表当前滑动窗口为s1的全排列之一
                if(allZero(count))
                    return true;
            }
            
            return false;
        }
    };
  • 相关阅读:
    bootstrap里的下拉菜单
    bootstrap里的图标
    bootstrap
    maven和svn区别
    maven
    计算机程序的思维逻辑 (20)
    计算机程序的思维逻辑 (19)
    计算机程序的思维逻辑 (18)
    计算机程序的思维逻辑 (17)
    计算机程序的思维逻辑 (15)
  • 原文地址:https://www.cnblogs.com/tornado549/p/10743531.html
Copyright © 2011-2022 走看看