c ++ sliding window Premium seek to find all the letters in the string word ectopic

/ * * 
 * Problem: find all the letters in the string ectopic words 
 * requirements: Given a string s and a non-empty string p, find all s is a substring of ectopic word letter p, and the sub-return starting index string. 
 * Note: string contains only lowercase letters, and the length of the string s and p is not more than 20,100. 
 * Method 1: Using the slide array do 
 * Solution class { 
Private: 
    Vector <int> List; 
    int A [26 is] = {0}; 
    int B [26 is] = {0}; 
public: 
    Vector <int> findAnagrams (String S, P String) { 
        IF (s.length () == 0 || p.length () == 0 || s.length () <p.length ()) return List; 
        for (int I = 0; I <p.length (); I ++) { 
            A [S [I] - 'A'] ++; 
            B [P [I] - 'A'] ++; 
        } 
        int left = 0; 
        int right = p.length (); 
        the while (right <s.length ()) 
        {
            IF (isValid (A, B)) list.push_back (left); 
            A [S [left ++] - 'A'] -; 
            A [S [right ++] - 'A'] ++; 
        } 
        IF (isValid (A , B)) list.push_back (left); 
        return List; 
    } 
public: 
    BOOL isValid (A int [], int B []) 
    { 
        for (int I = 0; I <26 is; I ++) 
            IF (A [ ! I] = B [I]) return to false; 
        return to true; 
    } 
}; 

 * method 2: using FIG thought to do, the p elements are placed in the map, once again, traversing s immediately next test 
 * method 3: KMP algorithm 
 * method 4: violence + hashMap (last case timeout) 
 * class Solution { 
    Private List <Integer> List = new new ArrayList <Integer> (); 
    Private the Map <Character, Integer> mm = new new HashMap <Character, Integer>();
    public List<Integer> findAnagrams(String s, String p) {
        if(s.length()<p.length())return list;
        for(int i=0;i<p.length();++i)
            mm.put(p.charAt(i), mm.get(p.charAt(i))==null?1:mm.get(p.charAt(i))+1);       
        int m=s.length();
        int n=p.length();
        for(int i=0;i<=m-n;++i)
            if(mm.containsKey(s.charAt(i))&&isValid(s,p,i,i+n-1))list.add(i);
        return list;
    }
    
    public boolean isValid(String s, String p,int left,int right)
    {
        Map<Character,Integer>map=new HashMap<Character,Integer>();
        for(int i=left;i<=right;++i)
            map.put(s.charAt(i), map.get(s.charAt(i))==null?1:map.get(s.charAt(i))+1);   
        if(mm.size()!=map.size())return false;
        for(int i=0;i<p.length();++i) {
            if(map.containsKey(p.charAt(i))&&map.get(p.charAt(i))!=0)map.put(p.charAt(i), map.get(p.charAt(i))-1);
            else return false;
        }            
        return true;
    }
}
 */

 

Guess you like

Origin www.cnblogs.com/z2529827226/p/11764184.html