heydoy / Codility-Swift

codility 사이트 exercise를 푸는 곳
0 stars 0 forks source link

String Symmetry Point #3

Open heydoy opened 1 year ago

heydoy commented 1 year ago
extension String {
    subscript(idx: Int) -> String? {
        guard (0..<count).contains(idx) else {
            return nil
        }
        let target = index(startIndex, offsetBy: idx)
        return String(self[target])
    }

    subscript(_ range: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        let end = index(startIndex, offsetBy: min(self.count, range.upperBound))
        return String(self[start..<end])
    }

    subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        return String(self[start...])
    }
}

public func solution(_ S : inout String) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    if S.count % 2 == 0 { return -1 }

    var mid = S.count / 2
    var start = 0
    var end = S.count - 1

    while start < mid {
        if S[start] != S[end] {
            return -1
        }
        start += 1
        end -= 1
    }

    return mid
}

스코어 57 첨자를 문자열 익스텐션으로 만들고 단순 비교로 for문을 돌렸더니 대용량 데이터에서 타임아웃 에러가 났다.

image

https://app.codility.com/demo/results/training5GFM46-FXK/

heydoy commented 1 year ago

문제: https://app.codility.com/programmers/trainings/4/str_symmetry_point/start/

heydoy commented 1 year ago

시간 복잡도가 O(length(S)**2)

heydoy commented 1 year ago

문자열에 첨자 익스텐션 한 것 때문에 복잡도가 늘어난 거 같아서 문자열을 Character Array로 바꾸고 풀었더니 100%가 나왔다

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ S : inout String) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    if S.count % 2 == 0 { return -1 }

    let mid = S.count / 2
    var start = 0
    var end = S.count - 1

    let S = Array(S)

    while start < mid {
        if S[start] != S[end] {
            return -1
        }
        start += 1
        end -= 1
    }

    return mid
}
image

https://app.codility.com/demo/results/training78BH6B-S4T/