首页 > 代码库 > Substring Anagrams
Substring Anagrams
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 40,000.
The order of output does not matter.
Example
Given s = "cbaebabacd"
p = "abc"
return [0, 6]
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".
思路: HashTable
RelatedProblems : Anagrams Two Strings Are Anagrams
public class Solution { /** * @param s a string * @param p a non-empty string * @return a list of index */ public List<Integer> findAnagrams(String s, String p) { List<Integer> result = new ArrayList<>(); if (s.length() < p.length()) { return result; } int[] numS = new int[256]; int[] numP = new int[256]; for (int i = 0; i < p.length(); i++) { numS[s.charAt(i) - ‘a‘]++; numP[p.charAt(i) - ‘a‘]++; } if (Arrays.equals(numS,numP)) { result.add(0); } for (int i = p.length(); i < s.length(); i++) { numS[s.charAt(i) - ‘a‘]++; numS[s.charAt(i - p.length()) - ‘a‘]--; if (Arrays.equals(numS,numP)) { result.add(i - p.length() + 1); } } return result; } }
Substring Anagrams
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。