问题:
难度:easy
说明:
输入字符串s,p,然后在s中查找所有符合p的异序词,返回是否存在异序词,一样使用滑动窗口Find All Anagrams in a String相似。
相关算法题:
[Leetcode学习-java]Find All Anagrams in a String(获取所有异序词):
https://blog.youkuaiyun.com/qq_28033719/article/details/106194878
输入案例:
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
我的代码:
一样使用滑动窗口,时间复杂度On,代码并没有什么特别的。
class Solution {
public boolean checkInclusion(String s1, String s2) {
// 先进行map存储
int s1len = s1.length();
int[] map = new int[128];
for(int i = 0;i < s1len;i ++) {
map[s1.charAt(i)] ++;
}
int left = 0;
int right = 0;
int s2len = s2.length();
char[] s2ch = s2.toCharArray();
// 进行连续判断,否则移动left
while(right < s2len) {
map[s2ch[right]] --;
while(map[s2ch[right]] < 0) {
map[s2ch[left ++]] ++;
}
right ++;
// 连续移动发现长度已经和s1一致,就返回true
if(right - left == s1len) return true;
}
// 判断完毕,没有为false
return false;
}
}