Guest User

Untitled

a guest
Oct 23rd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. """
  2. Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
  3.  
  4. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
  5.  
  6. The order of output does not matter.
  7.  
  8. Example 1:
  9.  
  10. Input:
  11. s: "cbaebabacd" p: "abc"
  12.  
  13. Output:
  14. [0, 6]
  15.  
  16. Explanation:
  17. The substring with start index = 0 is "cba", which is an anagram of "abc".
  18. The substring with start index = 6 is "bac", which is an anagram of "abc".
  19. Example 2:
  20.  
  21. Input:
  22. s: "abab" p: "ab"
  23.  
  24. Output:
  25. [0, 1, 2]
  26.  
  27. Explanation:
  28. The substring with start index = 0 is "ab", which is an anagram of "ab".
  29. The substring with start index = 1 is "ba", which is an anagram of "ab".
  30. The substring with start index = 2 is "ab", which is an anagram of "ab".
  31. """
  32. from collections import Counter
  33. class Solution(object):
  34. def findAnagrams(self, s, p):
  35. """
  36. :type s: str
  37. :type p: str
  38. :rtype: List[int]
  39. """
  40. rt = []
  41. pdict = {}
  42. if len(p) > len(s):
  43. return rt
  44. for var in p:
  45. pdict[var] = pdict.setdefault(var, 0) + 1
  46. counter = len(pdict)
  47. begin = end = 0
  48. while(end < len(s)):
  49. var = s[end]
  50. if var in pdict:
  51. pdict[var] -= 1
  52. if pdict[var] ==0:
  53. counter -=1
  54. end += 1
  55. while counter==0:
  56. var = s[begin]
  57. if var in pdict:
  58. pdict[var] += 1
  59. if pdict[var] > 0:
  60. counter +=1
  61. if end-begin == len(p):
  62. rt.append(begin)
  63. begin +=1
  64. return rt
Add Comment
Please, Sign In to add comment