• LeetCode 567. Permutation in String


    LeetCode 567. Permutation in String (字符串的排列)

    题目

    链接

    https://leetcode-cn.com/problems/permutation-in-string/

    问题描述

    给你两个字符串 s1 和 s2 ,写一个函数来判断 s2 是否包含 s1 的排列。如果是,返回 true ;否则,返回 false 。

    换句话说,s1 的排列之一是 s2 的 子串 。

    示例

    输入:s1 = "ab" s2 = "eidbaooo"
    输出:true
    解释:s2 包含 s1 的排列之一 ("ba").

    提示

    1 <= s1.length, s2.length <= 104
    s1 和 s2 仅包含小写字母

    思路

    还是滑动窗口,要求排序,那就用need存放应该有的字符和数量。从右侧进行增加,左侧进行减少。由于要包括排列,就代表子串的长度应该和s1一样长,可以减少部分运算。

    复杂度分析

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

    代码

    Java

    public static boolean checkInclusion(String s1, String s2) {
            Map<Character, Integer> window = new HashMap();
            Map<Character, Integer> need = new HashMap();
            int s1len = s1.length();
            int s2len = s2.length();
            for (int i = 0; i < s1len; i++) {
                char c = s1.charAt(i);
                need.put(c, need.getOrDefault(c, 0) + 1);
            }
            int left = 0, right = 0;
            int valid = 0;
            while (right < s2len) {
                char addch = s2.charAt(right);
                window.put(addch, window.getOrDefault(addch, 0) + 1);
                right++;
                if (need.containsKey(addch) && window.get(addch).equals(need.get(addch))) {
                    valid++;
                    if (valid == need.size()) {
                        return true;
                    }
                }
                while (right - left >= s1len) {
                    char rech = s2.charAt(left);
                    left++;
                    if (need.containsKey(rech)) {
    
                        if (window.get(rech).equals(need.get(rech))) {
                            valid--;
                        }window.put(rech, window.get(rech) - 1);
                    }
                }
            }
            return false;
        }
    
    
  • 相关阅读:
    真正明白了引用与对象的关系,就能避开下面这个陷阱
    python 垃圾回收
    字典
    表的操作
    MySQL数据库中的存储引擎
    MySQL数据库的基本操作
    MySQL数据库安装文件夹与配置文件简易说明
    数据库概述
    Arrays类
    Math类
  • 原文地址:https://www.cnblogs.com/blogxjc/p/15978720.html
Copyright © 2020-2023  润新知