首页 > 代码库 > Find All Anagrams in a String Leetcode
Find All Anagrams in a String Leetcode
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。