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

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

问题

给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。

说明:

字母异位词指字母相同,但排列不同的字符串。
不考虑答案输出的顺序。

输入:s: “cbaebabacd” p: “abc”

输出:[0, 6]

解释:
起始索引等于 0 的子串是 “cba”, 它是 “abc” 的字母异位词。
起始索引等于 6 的子串是 “bac”, 它是 “abc” 的字母异位词。

输入:s: “abab” p: “ab”

输出:[0, 1, 2]

解释:
起始索引等于 0 的子串是 “ab”, 它是 “ab” 的字母异位词。
起始索引等于 1 的子串是 “ba”, 它是 “ab” 的字母异位词。
起始索引等于 2 的子串是 “ab”, 它是 “ab” 的字母异位词。

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();
    }

}

以上给出2种算法实现,以下是这个案例的输出结果:

[0,1]
[0,1]

分析:

显而易见,TwoSum 的时间复杂度为: O(n^{2}),TwoSum2 的时间复杂度为: O(n)

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3790

(2)
上一篇 2020年06月08日 18:09
下一篇 2020年06月08日 18:10

相关推荐

发表回复

登录后才能评论