码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 438. Find All Anagrams in a String

时间:2020-04-03 15:13:48      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:--   while   tar   lock   array   code   val   ++   字符   

找到字符串中所有字母易位词。给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。例子,

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".

思路是滑动窗口(sliding window)。这个题也可以用之前的模板做,参见76,159,340。先遍历p,得到p中每个字母和他们对应的出现次数。再去遍历s,用start和end指针,end在前,当某个字母的value位0的时候,counter才能--。当counter == 0的时候,判断end - begin是否等于p的长度,若是,则将begin的坐标加入结果集。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public List<Integer> findAnagrams(String s, String p) {
 3         List<Integer> res = new ArrayList<>();
 4         // corner case
 5         if (p.length() > s.length()) {
 6             return res;
 7         }
 8 
 9         // normal case
10         Map<Character, Integer> map = new HashMap<>();
11         for (char c : p.toCharArray()) {
12             map.put(c, map.getOrDefault(c, 0) + 1);
13         }
14         int counter = map.size();
15         int begin = 0;
16         int end = 0;
17         while (end < s.length()) {
18             char c = s.charAt(end);
19             if (map.containsKey(c)) {
20                 map.put(c, map.get(c) - 1);
21                 if (map.get(c) == 0) {
22                     counter--;
23                 }
24             }
25             end++;
26 
27             while (counter == 0) {
28                 char temp = s.charAt(begin);
29                 if (map.containsKey(temp)) {
30                     map.put(temp, map.get(temp) + 1);
31                     if (map.get(temp) > 0) {
32                         counter++;
33                     }
34                 }
35                 if (end - begin == p.length()) {
36                     res.add(begin);
37                 }
38                 begin++;
39             }
40         }
41         return res;
42     }
43 }

 

JavaScript实现

 

[LeetCode] 438. Find All Anagrams in a String

标签:--   while   tar   lock   array   code   val   ++   字符   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12626540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!