# C#LeetCode刷题之#438-找到字符串中所有字母异位词（Find All Anagrams in a String）

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.

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”.

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”.

```public class Program {

public static void Main(string[] args) {
int[] nums = { 2, 7, 11, 15 };

var res = TwoSum(nums, 9);
var res2 = TwoSum2(nums, 9);

Console.WriteLine(\$"[{res[0]},{res[1]}]");
Console.WriteLine(\$"[{res2[0]},{res2[1]}]");

Console.ReadKey();
}

public static int[] TwoSum(int[] nums, int target) {
//类似于冒泡，双循环比较2个数的和与目标值是否相等
for (int i = 0; i < nums.Length; i++) {
for (int j = i + 1; j < nums.Length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
//找不到时抛出异常
throw new ArgumentException();
}

public static int[] TwoSum2(int[] nums, int target) {
//用数组中的值做key，索引做value存下所有值
var dictionary = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
//记录差值
int complement = target - nums[i];
//若字典中已经存在这个值，说明匹配成功
if (dictionary.ContainsKey(complement)) {
return new int[] { dictionary[complement], i };
}
//记录索引
dictionary[nums[i]] = i;
}
//找不到时抛出异常
throw new ArgumentException();
}

}```

```[0,1]
[0,1]```

(2)