Swift solution - Bit Manipulation


  • 0
    class Solution {
        func findRepeatedDnaSequences(_ s: String) -> [String] {
            if s.characters.count < 10 {
                return []
            }
            
            var words = Set<Int>()
            var doubleWords = Set<Int>()
            var result = [String]()
            var map = [Int](repeatElement(0, count: 26))
            var chars = Array(s.characters)
                
            map["C".asciiValue - "A".asciiValue] = 1
            map["G".asciiValue - "A".asciiValue] = 2
            map["T".asciiValue - "A".asciiValue] = 3
            
            for i in 0..<(s.characters.count - 9) {
                var val = 0
                for j in i..<(i + 10) {
                    val <<= 2
                    val |= map[String(chars[j]).asciiValue - "A".asciiValue]
                }
                if !words.insert(val).inserted && doubleWords.insert(val).inserted {
                    result.append(String(chars[i..<(i + 10)]))
                }
            }
            
            return result
        }
    }
    
    extension String {
        var asciiValue: Int {
            get {
                let value = self.unicodeScalars.filter{$0.isASCII}.first?.value ?? 0
                return Int(value) 
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.