标签:index res 字符 details lis ram output bsp ams
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".
题目含义:给出一个字符串s和一个非空的字符串p,找到p的重组字在s中出现的开始位置
1 public List<Integer> findAnagrams(String s, String p) { 2 // http://blog.csdn.net/chenwuji91/article/details/52981530 3 List<Integer> result = new ArrayList<>(); 4 if (s == null || s.length() == 0 || p == null || p.length() == 0) 5 return result; 6 int[] hash = new int[256]; 7 char[] pp = p.toCharArray(); 8 for (char i : pp) { 9 hash[i]++; 10 } 11 int left = 0, right = 0, count = p.length(); 12 while (right < s.length()) { 13 if (hash[s.charAt(right++)]-- > 0) //窗口右移;相应的hash值减小;如果这个位置的Hash值是正的,表示p字符串也包含这个,所以count做减法 14 count--; 15 if (count == 0) 16 result.add(left);//count指示器,为0表示和p对应的hash值完全一致 17 if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) 18 //如果当窗口大小和需要比较的字符串大小一致的时候,将窗口左边的指针向右边移动,移动的同时左边的字符计数因为在第一个if的地方hash值减小过,所以需要执行对应恢复操作,即:hash值增加,count计数值增加。 19 count++; 20 } 21 return result; 22 }
438. Find All Anagrams in a String
标签:index res 字符 details lis ram output bsp ams
原文地址:http://www.cnblogs.com/wzj4858/p/7718842.html