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

    Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

    In other words, return true if one of s1's permutations is the substring of 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].

    字符串的排列。

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/permutation-in-string
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题意是给两个字符串 s1 和 s2,s1 较短,请问 s2 中是否包含 s1 的某个排列。还是典型的 sliding window 的解法,首先创建一个 hashmap,统计 s1 中出现的字母和次数的情况,然后设置两个 pointer start 和end,夹住 s2 开始扫描,counter 变量初始化的时候记录的是 s1 的长度。其余思路参见76题,这道题唯一跟 76 题不同的地方是只要在 s2 中找到 s1 的某一个排列,就直接 return true了,不一定需要扫描完整个 s2。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean checkInclusion(String s1, String s2) {
     3         int len = s1.length();
     4         int[] map = new int[128];
     5         for (char c : s1.toCharArray()) {
     6             map[c]++;
     7         }
     8         int counter = s1.length();
     9         int start = 0;
    10         int end = 0;
    11         while (end < s2.length()) {
    12             char c1 = s2.charAt(end);
    13             if (map[c1] > 0) {
    14                 counter--;
    15             }
    16             map[c1]--;
    17             end++;
    18             while (counter == 0) {
    19                 if (end - start == len) {
    20                     return true;
    21                 }
    22                 char c2 = s2.charAt(start);
    23                 map[c2]++;
    24                 if (map[c2] > 0) {
    25                     counter++;
    26                 }
    27                 start++;
    28             }
    29         }
    30         return false;
    31     }
    32 }

    sliding window相关题目

    LeetCode 题目总结

  • 相关阅读:
    SpringMVC:com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
    SpringMVC DELETE,PUT请求报错 添加支持Http的DELETE、PUT请求
    HashMap源码总结
    ArrayList动态扩容大小
    Java中的可选操作
    Java中深拷贝与浅拷贝理解
    String在内存中如何存储
    异常处理—checked exception 和 unchecked exception
    Comparable和Comparator区别
    Scanner类与Readable接口
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12917037.html
Copyright © 2011-2022 走看看