Leetcode 438. Find All Anagrams in a String

21 篇文章 0 订阅
10 篇文章 0 订阅

O(t.length() * s.length())

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();
        
        // create an array to save the counts for each letter
        int[] cnt = new int[26];
        int[] tmp;
        
        // count the letter frequency in string p
        for (int i=0; i<p.length(); i++)
            cnt[p.charAt(i) - 'a']++;
            
        // starting from index 0 check if it is a start index
        for (int j=0; j<s.length(); j++) {
            tmp = cnt.clone();
            int len = 0;
            while (j+len < s.length() && len < p.length()) {
                if (tmp[s.charAt(j+len) - 'a'] != 0) {
                    tmp[s.charAt(j+len) - 'a']--;
                    len++;
                }
                else break;
            }
            // found a valid index
            if (len == p.length()) list.add(j);
        }
        
        return list;
    }
}
O(n), sliding window.

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<>();
        // create a hash table <letter, count>, key is the index(letter), value is count
        int[] hash = new int[128];     
        // count the number of times each letter appeared in p
        for (int i=0; i<p.length(); i++)
            hash[p.charAt(i)]++;
            
        int left = 0, right = 0, count = p.length();
        
        // increase and decrease the window at the same time (*)
        while (right < s.length()) {
            // found a letter in p
            if (hash[s.charAt(right)] > 0)
                count--;
            hash[s.charAt(right)]--;
            right++;
           //when the count is down to 0, means we found the right anagram
            //then add window's left to result list
            if (count == 0) {
                list.add(left);
            }
            //if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
            //++ to reset the hash because we kicked out the left
            //only increase the count if the character is in p
            //the count >= 0 indicate it was original in the hash, cuz it won't go below 0
            if (right - left == p.length() ) {
                if (hash[s.charAt(left)] >= 0) {
                    count++;
                }
                hash[s.charAt(left)]++;
                left++;
            }
        }
        return list;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值