package com.app.main.LeetCode.slidingwindow;
import java.util.Arrays;
import java.util.Collections;
/**
*567
*
* medium
*
* https://leetcode.com/problems/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.
*
*
*
* 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:
*
* The input strings only contain lower case letters.
* The length of both given strings is in range [1, 10,000].
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2020/1/20
* Time:下午8:35
*/
public class PermutationInString {
// sliding window O(n)
public boolean checkInclusion(String s1, String s2) {
int cn = s1.length();
int[] count = new int[26];
for (int i = 0; i < s1.length(); i++) {
count[s1.charAt(i) - 'a']++;
}
int[] count2 = new int[26];
int l = 0;
for (int r = 0; r < s2.length(); r++) {
if (count[s2.charAt(r) - 'a'] == 0) {
// optimize , needn't new int[26], just transfer l and backtrack data
// l = r + 1;
// count2 = new int[26];
// cn = s1.length();
while (l < r) {
count2[s2.charAt(l) - 'a']--;
cn++;
l++;
}
l++;
continue;
}
if (count2[s2.charAt(r) - 'a'] < count[s2.charAt(r) - 'a']) {
count2[s2.charAt(r) - 'a']++;
cn--;
if (cn == 0) {
return true;
}
continue;
}
// count2[s2.charAt(r) - 'a'] == count[s2.charAt(r) - 'a'] , curr ch is full, transfer l and backtrack data
while (l < r && s2.charAt(l) != s2.charAt(r)) {
count2[s2.charAt(l) - 'a']--;
cn++;
l++;
}
if (l < r) {
l++;
} else {
count2[s2.charAt(r) - 'a']++;
cn--;
}
}
return false;
}
}
LeetCode--567--medium--PermutationInString
猜你喜欢
转载自blog.csdn.net/huangdingsheng/article/details/104306082
今日推荐
周排行