Solution by evanglechen


  • 0
    E

    func findAnagrams(_ s: String, _ p: String) -> [Int]
    {
    var result = Int

        if p.count == 1 {
            for (index, char) in s.enumerated() {
                if (String(char) == p) {
                    result.append(index)
                }
            }
        } else if (p.count <= s.count) {
            var repeatP = true
            let charRepeat = p[p.startIndex];
            for char in p {
                if char != charRepeat {
                    repeatP = false
                    break
                }
            }
            
            if repeatP {
                var low = 0
                var up = 0
                var distance = 0
                while distance + 1 < s.count {
                    let str = String(s[s.index(s.startIndex, offsetBy: up) ... s.index(s.startIndex, offsetBy: s.count - 1)])
                    if let range = str.range(of: p) {
                        low = range.lowerBound.encodedOffset;
                        result.append(low + distance)
                        up = range.upperBound.encodedOffset
                        distance += up
                    } else {
                        break
                    }
                }
            } else {
                var flag = true
                var index = 0
                while index <= s.count - p.count {
                    let str = String(s[s.index(s.startIndex, offsetBy: index) ..< s.index(s.startIndex, offsetBy: index + p.count)])
                    if str != p {
                        result.removeAll()
                        flag = false
                        break
                    }
                    index += p.count
                }
                
                if flag {
                    for var i in 0 ..< s.count - p.count {
                        result.append(i)
                    }
                    return result
                }
                
                var pArray = p.cString(using: String.Encoding.utf8)!
                var sArray = s.cString(using: String.Encoding.utf8)!
                pArray.remove(at: pArray.count - 1)
                sArray.remove(at: sArray.count - 1)
                let pSort = pArray.sorted()
                for (index, num) in sArray.enumerated() {
                    if pArray.contains(num) && pArray.contains(sArray[index + 1]) {
                        let subArray = sArray[index ..< pArray.count + index]
                        if pSort == subArray.sorted() {
                            result.append(index)
                        }
                    }
                    if sArray.count - index <= pArray.count {
                        return result
                    }
                }
            }
        }
        return result
    }

Log in to reply
 

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