• Find All Anagrams in a String 找变位子串


    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.

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

    本题难度为easy  当看到题目的第一眼 有些怀疑  怎么能等级那么简单  找到思路后发现 确实不难  现整理总结思路

    原字符串s,在s中寻找字符串p的变位字符串的位置,并依次输出,且字符串元素均为小写字母。

    思路:首先题目中给定 只有小写字母 所以可以用一个数组长度26来包含完所有的元素情况 并记录其对应出现次数 当然首先应该记录的应该是p的元素的对应次数pvec

    然后再s中,从第一个元素开始往后找 在长度一样时 每次与pvec来比较 与p的元素和所对应的次数是否完全一样 在这个过程中 与顺序无关  且当s中元素往后移动一位 

    前面起始位置都应该后移一位

    过程:

    1、记录p中元素及其出现次数 :pvec

    2、在s中 从位置0开始依次后移 依次往后记录当前s中元素出现的次数svec

    3、在当前s记录过程中 长度达到p的长度时  就要从开始端移除最开始元素了

    4、比较svec中元素记录和pvec中是否相等 相等则表示在这一长度中 找到了p的一个变位子串位置 即为s中当前长度的开始位置 并记录下来

    5、转第二步 直至s中元素记录完毕

     

    代码:

    vector<int> findAnagrams(string s, string p) {
        vector<int> res;
        if (s.length() < p.length() || s.length() == 0 || p.length() == 0)
            return res;
        vector<int> svec(26), pvec(26);
       
        for (int i = 0; i < p.length(); ++i)
            pvec[p[i] - 'a']++;
        for (int i = 0; i < s.length(); ++i)
        {
            svec[s[i] - 'a']++;
            if (i >= p.length())
                svec[s[i - p.length()] - 'a']--;
            if (svec == pvec)
                res.push_back(i - p.length()+1);
        }
        return res;
    }
    
  • 相关阅读:
    vue打包不显示或图片不显示配置
    Vue::is特性用法
    毕业实习报告
    前端vscode常用快捷键总结
    1. 变量常量
    信息收集之CMS指纹识别
    4. EIGRP的复合度量值
    3. EIGRP报文,三张表,邻居建立
    信息收集之目录扫描
    2. EIGRP路由单播邻居和被动接口
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6406382.html
Copyright © 2020-2023  润新知