Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc" Output:
[0, 6] Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab" Output:
[0, 1, 2] Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

题目标签:Hash Table

  题目给了我们两个string s 和 p, 让我们在 s 中 找到所有 p 的变位词。

  利用两个HashMap 和 Sliding window:

    先把 p 的char 和 出现次数 存入 mapP;

    然后遍历string s,利用 sliding window 把 和 p 一样长度的 string 的 char 保存在 tempMap 里,比较 tempMap 和 mapP。

Java Solution:

Runtime beats 20.00%

完成日期:11/07/2017

关键词:HashMap

关键点:利用sliding window 把 tempMap 和 mapP 比较

 class Solution
{
public List<Integer> findAnagrams(String s, String p)
{
List<Integer> list = new ArrayList<>();
HashMap<Character, Integer> mapP = new HashMap<>();
HashMap<Character, Integer> tempMap = new HashMap<>(); for(char c: p.toCharArray()) // store p char and occurrence into mapP
mapP.put(c, mapP.getOrDefault(c, 0) + 1); for(int i=0; i<s.length(); i++) // iterate s and update a tempMap with p len
{
char c = s.charAt(i);
char leftC; tempMap.put(c, tempMap.getOrDefault(c, 0) + 1); if(i >= p.length()) // once reach to p's length, remove most left char
{
leftC = s.charAt(i - p.length());
// remove left char
if(tempMap.get(leftC) == 1)
tempMap.remove(leftC);
else
tempMap.put(leftC, tempMap.get(leftC) - 1);
} if(tempMap.equals(mapP))
list.add(i + 1 - p.length()); } return list;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

05-11 15:25
查看更多