Problem
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].
Solution
class Solution {
public boolean checkInclusion(String s1, String s2) {
int l1 = s1.length(), l2 = s2.length();
if (l2 < l1) return false;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < l1; i++) {
map.put(s1.charAt(i), map.getOrDefault(s1.charAt(i), 0)+1);
map.put(s2.charAt(i), map.getOrDefault(s2.charAt(i), 0)-1);
}
if (checkMap(map)) return true;
for (int i = l1; i < l2; i++) {
map.put(s2.charAt(i), map.getOrDefault(s2.charAt(i), 0)-1);
map.put(s2.charAt(i-l1), map.get(s2.charAt(i-l1))+1);
if (checkMap(map)) return true;
}
return false;
}
private boolean checkMap(Map<Character, Integer> map) {
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
if (entry.getValue() != 0) return false;
}
return true;
}
}
using int array as map
class Solution {
public boolean checkInclusion(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() > s2.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s1.length(); i++) {
count[s1.charAt(i)-'a']++;
count[s2.charAt(i)-'a']--;
}
if (allZero(count)) return true;
for (int i = s1.length(); i < s2.length(); i++) {
count[s2.charAt(i)-'a']--;
count[s2.charAt(i-s1.length())-'a']++;
if (allZero(count)) return true;
}
return false;
}
private boolean allZero(int[] arr) {
for (int i: arr) {
if (i != 0) return false;
}
return true;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。