Submission 30070342...

ChallengeString search
Submitter0x9e0ad99de20a444...
Submitted at2018-22-29
Gas used470434
/**
 * This file is part of the 1st Solidity Gas Golfing Contest.
 *
 * This work is licensed under Creative Commons Attribution ShareAlike 3.0.
 * https://creativecommons.org/licenses/by-sa/3.0/
 */

pragma solidity 0.4.24;
   
contract IndexOf {
    
    function indexOf(string haystack, string needle) public pure returns(int) {
        //v3.0
        uint haystackLen = bytes(haystack).length;
        uint needleLen = bytes(needle).length;
        int[] memory helper = new int[](123);
        int limit;
        
        if((haystackLen == 0) || (needleLen == 0)  ){
            return 0;
        }
        
        //Preprocessing
        uint i;
        int j;
        
        for(i = 0; i < 123; i++) 
            helper[i] = ~0; 
            
        j = 1;
        for(i = 0; i < needleLen; i++ ) { 
            helper[uint(bytes(needle)[i])] &= ~j; 
            limit |= j; 
            j <<= 1;
        } 
        limit = ~(limit>>1); 
        
        // Searching 
        int state;
        state = ~0;
        for (j = 0; j < int(haystackLen); j++) { 
            state = (state<<1) | helper[uint(bytes(haystack)[uint(j)])]; 
            if (state < limit) 
                return int(uint(j) - needleLen + 1); 
        }
        return -1;
    }
}