438 Find All Anagrams in a String
題目:
給String s和非空String p,找到所有p的回文在s中的起始點仰楚。
給的String只含有小寫字母趋距。s和p的長度不超過20,100月劈。答案的順序無關(guān)。
例子:
Input: s: "cbaebabacd" p: "abc"
Output: [0, 6]
Input: s: "abab" p: "ab"
Output: [0, 1, 2]
代碼:
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s.length() == 0) {
return res;
}
int[] chars = new int[256];
for (int i = 0; i < p.length(); i++) {
chars[p.charAt(i)]++; // p中每個字符的個數(shù)敌买,也就是待match的個數(shù)
}
// two points: left是s要匹配的左邊界
int left = 0, right = 0, count = p.length(); // count: 要匹配的個數(shù)
while (right < s.length()) {
if (chars[s.charAt(right)] >= 1) { // current hash value >= 1: p中存在這個char
count--; // move right everytime, 如果s中這個字符在p里出現(xiàn)了, decrease the count
}
chars[s.charAt(right)]--; // 待match個數(shù)減1简珠,負數(shù)說明不該有這個char,但是出現(xiàn)了
right++; // 右邊界右移虹钮,繼續(xù)匹配
if (count == 0) { // 全部匹配
res.add(left);
}
// if we find the window's size equals to p, then move left (narrow the window) to find the new match window
// ++ to reset the hash because we kicked out the left
// only increase the count if the character is in p
// the count >= 0 indicate it was original in the hash, cuz it won't go below 0
if (right - left == p.length()) { // 已經(jīng)check了p.len個聋庵,不管是不是匹配
if (chars[s.charAt(left)] >= 0) { // 曾經(jīng)作為匹配字符出現(xiàn)過,也就是在p里出現(xiàn)過
count++; // left被剔除芙粱,所以還需要left的字符進行匹配
}
chars[s.charAt(left)]++; // left被剔除祭玉,所以hash里面?zhèn)€數(shù)加回來
left++;
}
}
return res;
}
}
其他相關(guān)題目
567 Permutation in String
https://leetcode.com/problems/permutation-in-string/