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
s2中是否包含s1的排列
第二遍刷,做出来了,用的map。solution使用的数组,比较简洁。
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length())
return false;
int[] s1map = new int[26];
int[] s2map = new int[26];
for (int i = 0; i < s1.length(); i++) {
s1map[s1.charAt(i) - 'a']++;
s2map[s2.charAt(i) - 'a']++;
}
for (int i = 0; i < s2.length() - s1.length(); i++) {
if (matches(s1map, s2map))
return true;
s2map[s2.charAt(i + s1.length()) - 'a']++;//右边的字母加入
s2map[s2.charAt(i) - 'a']--;//去掉左边的字母
}
return matches(s1map, s2map);
}
public boolean matches(int[] s1map, int[] s2map) {
for (int i = 0; i < 26; i++) {
if (s1map[i] != s2map[i])
return false;
}
return true;
}
想法比较简单,在s2中,每次框住一个和s1等长的子串
通过一个大小为26的数组,记录不同字符在字符串中出现的次数
然后和s1的记录作对比,尝试匹配。类似滑动窗口,长度不变,向右滑动。
其实还可以优化。每次匹配的时候,因为我们知道左边去掉的字符,和右边新加入的字符,所以没有必要做重新的全量匹配。
public class Solution {
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length())
return false;
int[] s1map = new int[26];
int[] s2map = new int[26];
for (int i = 0; i < s1.length(); i++) {
s1map[s1.charAt(i) - 'a']++;
s2map[s2.charAt(i) - 'a']++;
}
int count = 0;
for (int i = 0; i < 26; i++)
if (s1map[i] == s2map[i])
count++;
for (int i = 0; i < s2.length() - s1.length(); i++) {
int r = s2.charAt(i + s1.length()) - 'a', l = s2.charAt(i) - 'a';
if (count == 26)//不同字母出现次数完全一致 匹配
return true;
s2map[r]++;//将r加入
if (s2map[r] == s1map[r])//新加入的r匹配上了
count++;
else if (s2map[r] == s1map[r] + 1)//没匹配上
count--;
s2map[l]--;//去掉一个l
if (s2map[l] == s1map[l])//去掉之后出现次数匹配
count++;
else if (s2map[l] == s1map[l] - 1)
count--;
}
return count == 26;
}
}
输入 ab,eidboaab
一开始,s2map记录的是ei
r=d l=e
之后仍然是滑动窗口,每次向右移动一位,尝试匹配