212.有效的字母异位词
如果两个字符串互为字母异位词那长度一定相同,然后遍历;两个字符串,每个字母的出现次数相同即为字母异位词,所以我们需新建一个长度26的数组来记录每个字母增减次数,遍历结束该数组所以元素均为零就符合条件。可以通过ASCII相对值s[i]-'a'映射数组0-25索引值,具体如下:
public class Solution {
public bool IsAnagram(string s, string t) {
int sl=s.Length,tl=t.Length;
if(sl!=tl) return false;
int[] a = new int[26];
for(int i = 0; i < sl; i++){
a[s[i] - 'a']++;
a[t[i] - 'a']--;
}
foreach (int i in a)//遍历新数组,确保所有元素均不为0
{
if (i != 0)
return false;
}
return true;
}
}
349. 两个数组的交集
该题利用了HashSet的不重复性
public class Solution {
public int[] Intersection(int[] nums1, int[] nums2) {
if(nums1==null||nums1.Length==0||nums2==null||nums1.Length==0)
return new int[0]; //注意数组条件
HashSet<int> one = Insert(nums1);//调用函数添加nums1元素到one集合
HashSet<int> two = Insert(nums2);
one.IntersectWith(two);//使用HashSet的交集方法
return one.ToArray();
}
public HashSet<int> Insert(int[] nums){
HashSet<int> one = new HashSet<int>();
foreach(int num in nums){
one.Add(num);
}
return one;
}
}