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.
给定两个字符串s1和s2,编写函数判定s2是否是s1的置换字符串。意即判定s1的某种排列是否出现在s2中。

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].

思路

  1. try find a window (i, j) where s2.substr(i, j + 1 - i) contains all chars in s1;
  2. once found, try reduce window(i, j) such that j + 1 - i == s1.size() while the window still contains all chars in s1 by moving i, return true;
  3. if windows no longer contain all chars in s1, keep moving j forward;
class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        vector<int> cnt(256,0);
        for( char c:s1){
            cnt[c]++;
        }
        int left=s1.size();
        for(int i=0,j=0;j<s2.size();j++){
            if(cnt[s2[j]]-- >0){
                left--;
            }
            while(left==0){
                if(j-i+1==s1.size()) return true;
                if(++cnt[s2[i++]]>0) left++;
            }
        }
        return false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 今天,我感冒了,鼻子塞得很难受,于是妈妈说帮我艾灸一下。 妈妈拿出一个个像通马桶的皮搋子一样的小东西和...
    hello点点阅读 308评论 0 2
  • 朋友推荐的自控力lab,大致浏览了下,就报了读写70天。这对于三分钟热度的双子座来说的我的确是不小的挑战。 群里族...
    小橙小橙小橙阅读 98评论 0 0
  • 人群中,生命中,总是有那么些人,明明顶着一张陌生的脸,却总会给人一种熟悉的感觉,有时候是走路的姿势,有时候是说话的...
    木子青白阅读 463评论 0 0
  • 最开心的事,就是和宝贝一起天马行空的画画!
    朱朱丹阅读 212评论 0 0