Q31 LeetCode438 找到字符串中所有字母异位词

没看懂

 

 1 class Solution {
 2     public List<Integer> findAnagrams(String s, String p) {
 3         List<Integer>res=new ArrayList<>();
 4         int[]cnt=new int[26];
 5         int n=p.length();
 6         int m=s.length();
 7         if(n>m){
 8             return res;
 9         }
10         for(int i=0;i<n-1;i++){
11             cnt[p.charAt(i)-'a']++;
12             cnt[s.charAt(i)-'a']--;
13         }
14         cnt[p.charAt(n-1)-'a']++;
15         int l=0;
16         for(int r=n-1;r<m;r++){
17             cnt[s.charAt(r)-'a']--;
18             int o=0;
19             for(int j=0;j<26;j++){
20                 o+=cnt[j]!=0?1:0;
21                 if(o>=1){//此处优化很重要
22                     break;
23                 }
24             }
25             if(o==0){
26                 res.add(l);
27             }
28             cnt[s.charAt(l++)-'a']++;
29         }
30         return res;
31     }
32 }

 

posted @ 2024-06-13 21:41  清川1  阅读(12)  评论(0)    收藏  举报