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;
        }
    }
  • 相关阅读:
    TCP全局同步
    pytest框架之fixture详细使用
    库操作和表操作
    封装之如何隐藏对象及封装的意义
    类的抽象
    组合
    在子类中重用父类的方法和属性
    类的继承和实现原理
    类的使用,对象的使用
    互联网协议的五层协议详解
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11386718.html
Copyright © 2011-2022 走看看