567.permutation-in-string.go 688 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. func checkInclusion(s1 string, s2 string) bool {
  2. m, n := len(s1), len(s2)
  3. if n < m {
  4. return false
  5. }
  6. freq := make([]int, 256)
  7. for _, r := range s1 {
  8. freq[r]++
  9. }
  10. beg, end := 0, -1
  11. cnt := make([]int, 256)
  12. for end < n {
  13. for beg = end + 1; beg < n && freq[s2[beg]] == 0; beg++ {
  14. }
  15. copy(cnt, freq)
  16. for end = beg; end < n; end++ {
  17. ch := s2[end]
  18. if freq[ch] == 0 {
  19. break
  20. }
  21. cnt[ch]--
  22. for cnt[ch] < 0 {
  23. cnt[s2[beg]]++
  24. beg++
  25. }
  26. if isEmpty(cnt) {
  27. return true
  28. }
  29. }
  30. }
  31. if isEmpty(cnt) {
  32. return true
  33. }
  34. return false
  35. }
  36. func isEmpty(cnt []int) bool {
  37. for i := 'a'; i <= 'z'; i++ {
  38. if cnt[i] != 0 {
  39. return false
  40. }
  41. }
  42. return true
  43. }