【发布时间】:2021-01-23 23:56:47
【问题描述】:
给定两个字符串 s1 和 s2,编写一个函数,如果 s2 包含 s1 的排列,则返回 true。换句话说,第一个字符串的一个排列是第二个字符串的子字符串。
Example 1: (Test Case Passed)
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2: (Test Case Failed)
Input: s1 = "adc", s2 = "dcda"
Output: True
Expected : False
这个问题可以在 leetcode 上找到:https://leetcode.com/problems/permutation-in-string/submissions/
我已经通过了 78/103 个测试用例。我在使用我猜的条件时犯了一些错误,任何人都可以解决它。
这是我的代码:
class Solution {
public boolean checkInclusion(String s1, String s2) {
int k = s1.length();
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0; i<k; i++){
char rightChar = s1.charAt(i);
map.put(rightChar, map.getOrDefault(rightChar,0)+1);
}
int windowStart=0;
int decrement=0;
HashMap<Character, Integer> resMap = new HashMap<>();
for(int windowEnd=0; windowEnd<s2.length(); windowEnd++){
char nextChar = s2.charAt(windowEnd);
resMap.put(nextChar, resMap.getOrDefault(nextChar,0)+1);
if(windowEnd-windowStart+1 >= k){
if(resMap.equals(map)){
return true;
}else{
char leftChar = s2.charAt(windowStart);
resMap.remove(leftChar);
windowStart++;
}
}
}
return false;
}
}
提前致谢:)
【问题讨论】:
-
感谢您诚实地要求为您解决问题。这样做的目的是让您思考并尝试自己解决。
-
一个建议:添加一个“调试”日志以打印您在每次迭代中比较的内容,这应该对您有所帮助
标签: java data-structures sliding-window