zoukankan      html  css  js  c++  java
  • 567. Permutation in String

    Given two strings s1 and s2, write a function to return true if s2contains 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].

    sliding window

    time = O(n), space = O(1)

    class Solution {
        public boolean checkInclusion(String s1, String s2) {
            int[] map1 = new int[26];
            int[] map2 = new int[26];
            
            for(char c : s1.toCharArray()) {
                map1[c - 'a']++;
            }
            
            int slow = 0, fast = 0;
            while(fast < s2.length()) {
                char cf = s2.charAt(fast);
                map2[cf - 'a']++;
                fast++;
                
                while(fast - slow > s1.length()) {
                    char cs = s2.charAt(slow);
                    map2[cs - 'a']--;
                    slow++;
                }
                
                if(fast - slow == s1.length() && match(map1, map2)) {
                    return true;
                }
            }
            return false;
        }
        
        public boolean match(int[] map1, int[] map2) {
            for(int i = 0; i < 26; i++) {
                if(map1[i] != map2[i]) {
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    用了7年做到项目经理,女朋友却离开了我
    手把手教你建网站--程序小白适用篇
    燃尽图的学习与理解
    每周进度
    四人组队
    读构建之法之感
    两人组队,小学生的四则运算
    词汇统计
    AMQP中的架构和组成元素
    MSSQL机制
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11386718.html
Copyright © 2011-2022 走看看