jweinst1
6/1/2016 - 9:40 PM

string power set in swift, makes regex search go in O(1) with extreme space.

string power set in swift, makes regex search go in O(1) with extreme space.

//struct that holds the set of all possible subtrings
//does this process directly in the initialization of struct

struct StringPowerSet {
    let string:String
    var substrs:Set<String>
    
    init(string:String){
        self.string = string
        self.substrs = Set<String>()
        let length = self.string.characters.count
        let chars = Array(string.characters)
        //for loop to put in single characters
        for elem in chars {
            self.substrs.insert(String(elem))
        }
        
        //repeating loop to get substrs of other sizes.
        for i in 1..<length {
            var substart = 0
            var subend = i
            //intermediate loop to cut substrs of specific sizes
            while subend < length {
                self.substrs.insert(String(chars[substart...subend]))
                substart += 1
                subend += 1
            }
        }
    }
    
    //checking function to determine if substr is in string in O(1) time
    func hasString(string:String) -> Bool {
        return self.substrs.contains(string)
    }
}


let text = StringPowerSet(string:"i love apples and oranges because they are awesome")
text.hasString("apps")
//false