码迷,mamicode.com
首页 > 其他好文 > 详细

Find All Anagrams in a String Leetcode

时间:2017-01-18 12:05:01      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:nsis   cas   case   input   tar   integer   let   empty   length   

Given a string s and a non-empty string p, find all the start indices of p‘s anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

 

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

 

这道题有个很巧妙的移动窗口法,count表示当前left开始的第二个stirng长度的字符串中,有几个不是存在于第二个string里面的,初始值为第二个string的长度。这道题需要回顾一下。

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        if (s == null || p == null || s.length() == 0 || p.length() == 0) {
            return res;
        }
        int[] hash = new int[26];
        for (int i = 0; i < p.length(); i++) {
            hash[p.charAt(i) - ‘a‘]++;
        }
        int left = 0, right = 0, count = p.length();
        while (right < s.length()) {
            if (hash[s.charAt(right) - ‘a‘] >= 1) {
                count--;
            }
            hash[s.charAt(right) - ‘a‘]--;
            right++;
            
            if (count == 0) {
                res.add(left);
            }
            
            if (right - left == p.length()) {
                if (hash[s.charAt(left) - ‘a‘] >= 0) {
                    count++;
                }
                hash[s.charAt(left) - ‘a‘]++;
                left++;
            }
        }
        return res;
    }
    
}

还有一个问题就是

hash[s.charAt(left) - ‘a‘]++;

这句话为什么不能写在if的里面,到时候再来考虑一下。。。现在还不是很能理解。。。

Find All Anagrams in a String Leetcode

标签:nsis   cas   case   input   tar   integer   let   empty   length   

原文地址:http://www.cnblogs.com/aprilyang/p/6296194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!