首页 > 其他 > 详细

[leetcode]438. Find All Anagrams in a String找出所有变位词

时间:2018-10-18 14:39:23      阅读:168      评论:0      收藏:0      [点我收藏+]

如题

 

思路:

 

代码:

 1 class Solution {
 2        public List<Integer> findAnagrams(String s, String p) {
 3            //corner case
 4            List<Integer> res = new ArrayList<>();
 5            if (s == null || s.length() == 0 || p == null || p.length() == 0) return res;
 6            // initialize
 7            int left = 0;
 8            int right = 0;
 9            int count = p.length();
10            int[] map = new int[256];
11            // each char‘s frequency
12            for(int i = 0; i < p.length(); i++){
13                map[p.charAt(i)]++;
14            }
15          
16            // build window 
17            while (right < s.length()){
18                // this char exists in p  
19                if (map[s.charAt(right)] > 0){
20                   count --; 
21                }    
22                 map[s.charAt(right)] --;     
23                // if the window size equals to p
24                // 如果此时左右指针的差值等于p的长度
25                if (right - left == p.length()-1){
26                    // find 1st res
27                    if (count == 0)
28                        // add the left index
29                        res.add(left);               
30                    // move left pointer to start new search
31                    // 如果当这个字符原来是p中的话,现在移动指针需要还原以前原有的matchSize,开始新的搜索
32                    if (map[s.charAt(left)] >= 0) 
33                        matchSize ++;
34                    // 还原以前每个元素减去的1
35                    map[s.charAt(left)]++;
36                    left++;
37                }
38               right++;
39            }
40            
41            return res;
42     }
43 }

 

[leetcode]438. Find All Anagrams in a String找出所有变位词

原文:https://www.cnblogs.com/liuliu5151/p/9810073.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!