|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace HashTable.Lib |
| 7 | +{ |
| 8 | + // Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. |
| 9 | + |
| 10 | + //Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. |
| 11 | + |
| 12 | + //The order of output does not matter. |
| 13 | + |
| 14 | + //Example 1: |
| 15 | + |
| 16 | + //Input: |
| 17 | + //s: "cbaebabacd" p: "abc" |
| 18 | + |
| 19 | + //Output: |
| 20 | + //[0, 6] |
| 21 | + |
| 22 | + //Explanation: |
| 23 | + //The substring with start index = 0 is "cba", which is an anagram of "abc". |
| 24 | + //The substring with start index = 6 is "bac", which is an anagram of "abc". |
| 25 | + //Example 2: |
| 26 | + |
| 27 | + //Input: |
| 28 | + //s: "abab" p: "ab" |
| 29 | + |
| 30 | + //Output: |
| 31 | + //[0, 1, 2] |
| 32 | + |
| 33 | + //Explanation: |
| 34 | + //The substring with start index = 0 is "ab", which is an anagram of "ab". |
| 35 | + //The substring with start index = 1 is "ba", which is an anagram of "ab". |
| 36 | + //The substring with start index = 2 is "ab", which is an anagram of "ab". |
| 37 | + public class FindAllAnagramsSln |
| 38 | + { |
| 39 | + //s = "cbaebabacd", p = "abc" |
| 40 | + public IList<int> FindAnagrams(string s, string p){ |
| 41 | + IList<int> rtn = new List<int>(); |
| 42 | + int[] hash = new int[123]; //a~z: 97~122 |
| 43 | + foreach (var c in p){ |
| 44 | + hash[Convert.ToInt32(c)]++; //hash: key:char, value: occuring times |
| 45 | + } |
| 46 | + int eachBeg = 0, eachEnd = 0, count = p.Length; |
| 47 | + while (eachEnd < s.Length){ |
| 48 | + char tmpchar = s[eachEnd]; |
| 49 | + if (hash[tmpchar] >= 1) |
| 50 | + count--; |
| 51 | + hash[tmpchar]--; |
| 52 | + eachEnd++; //every time the eachEnd pointer to move toward right |
| 53 | + if (count == 0) |
| 54 | + rtn.Add(eachBeg); |
| 55 | + //reset the hash. |
| 56 | + |
| 57 | + if (eachEnd - eachBeg == p.Length){ |
| 58 | + char tmp = s[eachBeg]; |
| 59 | + if (hash[tmp] >= 0) |
| 60 | + count++; |
| 61 | + hash[tmp]++; |
| 62 | + eachBeg++; |
| 63 | + } |
| 64 | + } |
| 65 | + return rtn; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments